What is the proper way for fetching or ignoring lazy loaded objects using hibernate and spring -


i using spring mvc + hibernate + jackson. spring version : 4.3.x hibernate version : 4.3.x want create 2 api- 1 fetching beanb objects while 1 not fetching beanb object. using fetchtype.lazy same.

i have following beans:

@entity class beana {  @id int id;  @manytoone(fetch = fetchtype.lazy) @joincolumn(name = "beanb_id") private beanb beanb;   //getters , setters }  @entity class beanb {  @id int i;  //getters , setters } 

in controller have 2 methods: (removing service layer make question small. in service layer class, have @transactional)

@requestmapping(value = "/beana/{id}" , method=requestmethod.get)     public responseentity<beana> finddetailedbeanabyid(@pathvariable("id") int id )      {         // return beana object beanb         beana beana = beanadao.finddetailedbeanabyid(id);                return new responseentity<beana>(beana, httpstatus.ok);     }  @requestmapping(value = "/beana/{id}" , method=requestmethod.get)     public responseentity<beana> findnondetailedbeanabyid(@pathvariable("id") int id )      {         // return beana object without beanb         beana beana = beanadao.findnondetailedbeanabyid(id);                 return new responseentity<beana>(beana, httpstatus.ok);     } 

in dao

public beana finddetailedbeanabyid(long id) {           beana beana = (beana) getsession().get(beana.class, id);         hibernate.initialize(beana.getbeanb())         return beana;     }  public beana findnondetailedbeanabyid(long id) {      beana beana = (beana) getsession().get(beana.class, id);             return beana; } 

when hitting findnondetailedbeanabyid controller method, getting error :

org.springframework.http.converter.httpmessagenotwritableexception: not write content: not initialize proxy - no session 

when hitting findnondetailedbeanabyid controller method, getting error :

org.springframework.http.converter.httpmessagenotwritableexception: not write content: no serializer found class org.hibernate.proxy.pojo.javassist.javassistlazyinitializer , no properties discovered create beanserializer (to avoid exception, disable serializationfeature.fail_on_empty_beans)` 

what changes needed done?

for detailed findby method can build custom query , fetching beanb inside of query, getsession().createquery("select beana left join fetch a.beanb a.id == :id")

for lazy findby method think need add @transactional(readonly=true) @ controller level, because trying use beana after getting service annotated transactional. think tries fetch beanb database hibernate session might closed.

i not able tryout of suggestions because i'm @ phone.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -