Hibernate : Fetch collection -
i encontered problem while trying collection of elements : set of friend empty.
there 3 classes :
@entity @table(name="user") public class user { @id @column(name="user_id", nullable=false) private string mail; @column(name="password") private string password; @column(name="surname") private string surname; @column(name="name") private string name = null; @column(name="statut") private statutuser statut; @column(name="phonenumber") private int phonenumber; @onetomany(cascade = cascadetype.persist, mappedby="friendpk.friend") @fetch(fetchmode.join) private set<friend> friends = new hashset<friend>(); ... getters , setters
the second 1 :
@entity @table(name = "friend") public class friend { @embeddedid public friendpk friendpk; @column(name = "friend_statut") private statutfriend statutfriend; ... }
the last 1 :
@suppresswarnings("serial") @embeddable public class friendpk implements serializable{ @manytoone @joincolumn(name="user1_id", referencedcolumnname="user_id") protected user user1; @manytoone @joincolumn(name="user2_id", referencedcolumnname="user_id") protected user friend; }
when try friends' user, collection empty.
here's file method add relationship :
private entitymanagerfactory emf; private entitymanager manager; public string addfriends(string mail1, string mail2){ entitytransaction t; t = manager.gettransaction(); try{ t.begin(); user user = manager.find(user.class, mail1); user friend = manager.find(user.class, mail2); friend f = new friend(); f.setstatutfriend(statutfriend.tocheck); friendpk friendpk = new friendpk(); friendpk.setfriend(friend); friendpk.setuser1(user); f.setfriendpk(friendpk); set<friend> relationship = new hashset<friend>(); relationship = user.getfriends(); relationship.add(f); set<friend> relationship2 = new hashset<friend>(); relationship2 = friend.getfriends(); relationship2.add(f); user.setfriends(relationship); friend.setfriends(relationship2); manager.persist(user); t.commit(); error.setreq(statutreq.done); } catch(exception e){ error.setreq(statutreq.aborted); error.seterror(e.getmessage()); } { if (t.isactive()) { t.rollback(); } }
please indulgent code... i'm beginner ! lot.
at first sight, code seems correct despite architecture looks strange. class friendfk stand ? doesn't user need hold set of users set ? database point of view, relational table necessary not in java model.
if you, delete class , use hbm2dll tool generate correct matching database schema.
could specify hibernate , jars versions , give hibernate config file check it.
Comments
Post a Comment