When using spring+hibernate, we usually use lazy loading when we get values for a one-to-many, many-to-many, and many-to-numerous associated entities. The advantage of this is that when we need to correlate the properties of the object, we can then query the database so that we don't have to query a lot of data at once.
This often encounters an exception: Could not initialize proxy-no Session, this article on this exception to do a variety of processing methods of summary, combined with actual needs to eliminate errors.
specific reasons: using lazy Loading method, the first time to get the principal object after the session has been closed, so to query the properties of the associated object, no session can be used.
Workaround:
1. Use fetch = Fetchtype.eager, that is, do not use lazy loading, so that all properties are loaded at once, including the subject, the associated entity.
benefit: Avoid lazy loading session does not exist.
Cons: The lazy load feature is missing, and loading data too much at once can have an effect on program efficiency.
2. Manually control the switch of the session. Open a session yourself, and then manually display the session after you have finished using it.
Session session = Sessionfactory.opensession ();//through the session to query the corresponding entity user user = Session.find (ID);//Get the associated object List<role > roles = User.getroles ();//Use the associated object for (Role role:roles) {System.out.println (Role.getname ());}
benefit: use lazy load feature and get it when needed.
Cons: need to manually control the session switch.
Scenario: When the spring container starts, it needs to get the properties associated with an object. or JUnit unit tests.
3. Add Opensessioninview filter to enable the switch control of the session via the filter.
<filter> <filter-name>openSessionInView</filter-name> <filter-class> org.springframework.orm.hibernate4.support.opensessioninviewfilter</filter-class></filter>< Filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</ Url-pattern></filter-mapping>
Benefits: We do not need to manually control the session switch.
Disadvantage: The filter cannot be completed if the Web container is not being used, or if the Web container is not started, or if no request is sent at all. This is only possible with workaround two.
Scenario:A Web application, where a request occurs and a request is blocked by the filter
This article is from the "Sg-yyz" blog, make sure to keep this source http://sgyyz.blog.51cto.com/5069360/1597628
Could not initialize proxy-no Session problem Resolution