简体   繁体   中英

Problems in many-to-many relations when updating parent object in hibernate?

I have many-to-many relationship between user and topic tables. Join table is user_topic. Topic entity has this:

@ManyToMany(fetch = FetchType.LAZY, targetEntity = IntermediateUser.class)
    @JoinTable(name = "user_topic", catalog = DataBaseConstants.DBCATALOG, joinColumns = { @JoinColumn(name = "topic_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) })
    @Cascade(value = CascadeType.DELETE)
    public Set<IntermediateUser> getVotingUsers() {
        return votingUsers;
    }

I update collection 'votingUsers' in transient topic instance and then call hibernate session's update method. I don't use method setVotingUsers but instead I clear votingUsers collection by method votingUsers.clear() and then add by votingUsers.add(voter); To update I call this method:

sessionFactory.currentSession().update(topic);

As a result I see in my log the following lines

DEBUG org.hibernate.SQL- update javahelpdb.topic set content=?, `PUBLISH_DATE`=?, rate=?, forum=?, title=?, user=?, viewquantity=? where topic_id=?
DEBUG org.hibernate.SQL- delete from javahelpdb.user_topic where topic_id=?
DEBUG org.hibernate.SQL- insert into javahelpdb.user_topic (topic_id, user_id) values (?, ?)

All parameters are correct. I expect to have only one query like:

update user_topic set topic_id=?, user_id=? where topic_id=?

How to instruct hibernate do update user_topic instead of delete and insert?

Thank you!

I think this is the normal Way how hibernate behaves. So you can't really do anything about it and if the relationships and the parameters are correct why bother?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM