我注意到Hibernate在ManyToMany关系中表现不够理想......这导致了问题,因为我的关系表也有最后更新的时间戳(由MySQL自动维护),但是Hibernate正在删除/插入太多,拧紧我的时间戳。
我的设置:
当我删除A(id = 1)和B(id = 10)之间的一个关系时,Hibernate执行以下操作:
我想要发生的是:
可以用Hibernate完成吗?
以下是实体:
@Entity
public class A {
@Id @GeneratedValue
private int id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name="a_b_ref")
private List<B> b;
...
}
@Entity
public class B {
@Id @GeneratedValue
private int id;
@ManyToMany(fetch = FetchType.LAZY, mappedBy="b")
private List<A> a;
...
}
测试代码:
@PersistenceContext
EntityManager em;
@Test
@Transactional
public void test1() {
A a = new A();
a.setB(new ArrayList<B>());
for (int i = 0; i < 10; i++) {
B b = new B();
em.persist(b);
a.getB().add(b);
}
em.persist(a);
em.flush();
a.getB().remove(9);
em.flush();
}
最后一次刷新发出了这个SQL:
delete from a_b_ref where a_id=?
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
insert into a_b_ref (a_id, b_id) values (?, ?)
而我想要的是:
delete from a_b_ref where a_id=? and b_id=?