The following error occurred: Org.hibernate.LazyInitializationException:could not initialize proxy-no Session
The reason is lazy loading problem, because hibernate mechanism is when we query an object, by default, the return is only the ordinary properties of the object, when the user to use the object properties, will be to the database once again query, you can then the session has been closed, The database could not be queried.
Example: Display the department name of the employee in the interface ${loginuser.department.name}
Workaround: (strongly recommend method three and method four, if it is simple to resolve can take method one)
Method One: Modify the object relationship file and make the following changes in Department.hbm.xml:
<name= "Department" lazy= "false" table= " Department ">
Method Two: not recommended. Display initialization, where you get the employee, add:
Hibernate.initialize (Employee.getdept ());
Method Three: Opensessionview, that is to say, expand the scope of the session (this method is not suitable for the introduction of spring)
Before processing, the scope of the session, only at the beginning of service call, service end. Filters can be used to enlarge the scope of the session, so that he can work throughout the process
Public classMyFilter1extendsHttpServletImplementsFilter { Public voidDoFilter (ServletRequest arg0, Servletresponse arg1, Filterchain arg2)throwsIOException, Servletexception {session session=NULL; Transaction Transaction=NULL; Try{Session=hibernateutil.getcurrentsession (); Transaction=session.begintransaction (); Arg2.dofilter (arg0, arg1); //This is not submitted until all requests are returned.Transaction.commit (); } Catch(Exception e) {if(Transaction! =NULL) {transaction.rollback (); } Throw Newruntimeexception (E.getmessage ()); }finally{ //You cannot use the regular shutdownhibernateutil.closecurrentsession (); } } Public voidInit (Filterconfig arg0)throwsservletexception {//TODO auto-generated Method Stub }}
Method Four:
Lazy load Resolution (FULL) Org.hibernate.LazyInitializationException:could not initialize Proxy-no Session