@ManyToMany association delete then reinsert problem

2008年12月9日 | 分类: java | 标签: , ,

I have a @ManyToMany property. When I do an update, hibernate issues a delete statement to delete all the related records in the cross reference table for the collection and then issues an insert statements to re-insert all the records back into the cross reference table again. The update performs correctly, but the id which is the primary key is always got changed by the trigger I set for the cross reference table, even I don’t do any update to any of the fields.

Hibernate: delete from A_B where A_ID=?
Hibernate: insert into A_B (A_ID, B_ID) values (?, ?)


Initially, I thought I was a cascade problem. I basically tried all possible cascade types, but no one fixed. Then the suggestion I had from hibernate forum was to do all collection initialization in one hibernate session.

Session session = getHibernateTemplate().getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
try {
A a= (A) session.createCriteria(Aclass).add(Restrictions.eq("id", id)).uniqueResult();
B b = (B) session.createCriteria(B.class).add(Restrictions.eq("id", programId)).uniqueResult();
A.getBCollection().remove(b);
tx.commit();
} catch (HibernateException he) {
if (tx != null) {
tx.rollback();
}
throw he;
} finally {
session.close();
}

It didn’t help either. (But I did gain hibernate knowledge from it.)

Finally, I came cross a post stating that he had the same problem and “change the property type from Collection to Set‘ solved his problem. I am not sure why it works with Set but not Collection, but it does solve my problem as well. I might be going to do more research on that later.

目前还没有任何评论.