I am very new to Spring, and I try to do many-to-many work as I expect. Relations work fine, tables are created, and data is inserted correctly. What I expect is that when I empty the List (that is, I release the ArrayList users from the Group object), I expect the system to remove the relationships from the database, but this is not the case.
I have the following classes:
@Entity @Table(name = "`group`") public class Group { @Id @GeneratedValue @Column(name = "id") private int id; @Column(name = "name") private String name; @ManyToMany(cascade = {CascadeType.ALL}) @JoinTable( name = "`user_has_group`", joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") ) private List<User> users = new ArrayList<User>(); ... } @Entity @Table(name = "`user`") public class User { @Id @GeneratedValue @Column(name = "id") private int id; @Column(name = "name") private String name; @ManyToMany(mappedBy = "users") private List<Group> groups = new ArrayList<Group>(); ... }
Here is the DAO:
@Repository public class GroupJpaDao implements GroupDao { private EntityManager em; @Transactional public void save(Group group) { this.em.merge(group); } ... @PersistenceContext void setEntityManager(EntityManager entityManager) { this.em = entityManager; } } @Repository public class UserJpaDao implements UserDao { private EntityManager em; @Transactional public void save(User user) { this.em.merge(user); } ... @PersistenceContext void setEntityManager(EntityManager entityManager) { this.em = entityManager; } }
Here is a test method:
@Test public void test() { Group g = new Group(); g.setName("Test group"); groupDao.save(g);
Am I doing something wrong or is it impossible to do?
Any tips are really appreciated.
Thanks!
source share