java - Hibernate : Update many-tomany intermediary table on Delete -
i new hibernate , not understand how should proceed update intermediary table.
i have manytomany relationship between 2 tables : conferences & publications
pojo publication.class :
private list<conference> conferences; ... @manytomany(targetentity = conference.class, cascade = { cascadetype.persist, cascadetype.merge }) @jointable(name = "publications_conferences", joincolumns = @joincolumn(name = "publications_id"), inversejoincolumns = @joincolumn(name = "conferences_id")) public list<conference> getconferences() { return conferences; } public void setconferences(list<conference> conferences) { this.conferences = conferences; } pojo conference.class :
private list<publication> publications; ... @manytomany(targetentity = publication.class, mappedby = "conferences") public list<publication> getpublications() { return publications; } public void setpublications(list<publication> publications) { this.publications = publications; } my table "conferences" contains duplicated records. code check whether 2 conference a,b have similar titles , deletes either or b. now, instead of deleting reference (and therefore record) in intermediary table, update way :
before deleting conference "b":
|publications_id|conferences_id ------------------------------- c | d | b after deleting conference "d":
|publications_id|conferences_id ------------------------------- c | d | <----- update reference i tried following code :
if (answer == 2) { deleteconferenceq.setparameter("confid", confidb); (publication pubb : publicationsb) { publicationsa.add(pubb); pubb.getconferences().add(a); session.save(pubb); } int result = deleteconferenceq.executeupdate(); tx.commit(); } but receive org.hibernate.hibernateexception: illegal attempt associate collection 2 open sessions. therefore wondering if correct.
edit #1: replaced previous code :
if (answer == 2) {
iterator<publication> pubbiter = publicationsb.iterator(); while (pubbiter.hasnext()) { publication pubb = pubbiter.next(); pubbiter.remove(); pubb.getconferences().remove(b); b.getpublications().remove(pubb); pubb.getconferences().add(a); publicationsb.add(pubb); } session.save(a); session.delete(b); } i still have previous exception upon session.save(obj)
can me ? thanks
from jpa/hibernate point of view, shouldn't think join table. need maintain both sides of @manytomany relationship , let hibernate manage database. in case should come down deleting 1 row , adding 1 row join table. code should this
publication pub = ...; conference conftoberemoved = ...; conference conftobeadded = ...; pub.getconferences().remove(conftoberemoved); // implies equals() , hashcode() implemented conftoberemoved.getpublications().remove(pub); // same here pub.getconferences().add(conftobeadded); conftobeadded.getpublications().add(pub); // save
Comments
Post a Comment