java - Load lazy objects only when needed -
i using hibernate 4.3.now scenario in app have 1 parent table contains foreign key referenced address table.address having @manytoone(fetch = fetchtype.lazy) in parent dto.now want is
case 1) need fetch data parent table when user of type parent login don't want load address in case.
case 2) when parent goes edit his/her personal information need load parent along address
i tried fallowing code
servlet
gsonbuilder builder = new gsonbuilder(); builder.registertypeadapterfactory(hibernateproxytypeadapter.factory); gson gson = new gson(); int parentid = integer.parseint(request.getparameter("parentid")); return gson.tojson(api.getparentdetails(parentid));
getparentdetails() method
public hashmap getparentdetails(int parentid) throws exception { parent parentdetails; responsehashmap = util.getinitialhashmap(); try { session.gettransaction().begin(); query q = session.createquery("from parent p p.parentid=:parentid"); q.setparameter("parentid", parentid); parentdetails = (parent) q.uniqueresult(); //hibernate.initialize(parentdetails.getaddress()); responsehashmap.put("responsedata", parentdetails); responsehashmap.put("responsecount", 0); if (parentdetails != null) { responsehashmap.put("errorcode", 107); } else { responsehashmap.put("errorcode", 0); } session.gettransaction().commit(); } catch (exception e) { session.gettransaction().rollback(); throw e; } return responsehashmap; }
now can see commented line
//hibernate.initialize(parentdetails.getaddress());
when uncomment line code works fine fails in case 1 me loads unnecessary data me address of parent dont want in case
when comment line
//hibernate.initialize(parentdetails.getaddress());
i getting error
org.hibernate.lazyinitializationexception: not initialize proxy - no session
i know above error occurring because hibernate goes lazy objects session not alive there.
then how achieve case 1 (see above) in app.
Comments
Post a Comment