我是Spring的新手,我正在尝试按照我的预期建立多对多的关系.关系工作正常,创建表并正确插入数据.我期望的是,当我清空List(即我从“Group”类型的对象中清空ArrayList“users”)时,我希望系统从数据库中删除关系 – 但事实并非如此.
我有以下课程:
@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
以下是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!
}
我做错了什么或是不可能的事情?
任何暗示都非常感激.
谢谢!
最佳答案
原文链接:https://www.f2er.com/spring/432295.html