我對Spring很陌生,我試圖按照我的預期做出多對多的關係。關係正常工作,創建表並正確插入數據。我期望的是,當我清空List時(即,我從「Group」類型的對象中清空ArrayList「users」),我期望系統從數據庫中刪除關係 - 但事實並非如此。Spring + JPA多對多關係
我有以下類別:
@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>();
...
}
下面是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;
}
}
下面是測試方法:
@Test
public void test()
{
Group g = new Group();
g.setName("Test group");
groupDao.save(g); // Works fine - inserts the group into the database
User u = new User();
u.setName("Test user");
userDao.save(u); // Works fine - inserts the user into the database
g.addUser(u);
groupDao.save(g); // Works fine - adds the many-to-many relationship into the database
g.removeAllUsers();
groupDao.save(g); // Doesn't work - I'm expecting it to remove all the related relationships from the database but it doesn't!
}
難道我做錯了什麼或者是它一些不可能做的事情?
任何提示真的很感激。
謝謝!
你嘗試在你的級聯屬性中添加'delete-orphan'嗎? – fasseg 2012-01-12 17:48:57
你是否聲明瞭'IdTransferringMergeEventListener'? – axtavt 2012-01-12 17:56:26
不知道這是問題的原因,但保存方法不應該返回void。它應該返回合併調用的結果。嘗試執行此更改並使用返回的組:'g = groupDao.save(g);' – 2012-01-12 18:10:55