Hibernate delayed loading error failed to lazily initialize a collection of Role

Source: Internet
Author: User
Hibernate delayed loading error failed to lazily initialize a collection of Role
14:27:04Tags: J2EE

[Push to technical circle
]

Copyright:
Original works. If you need to reprint them, please contact the author. Otherwise, legal liability will be held.
This problem usually occurs in one-to-multiple scenarios. There are two solutions:
1. Set lazy to false.
If annotation is used, the configuration is as follows:
@ Onetoworkflow (
Targetentity = courseauthorizationitem. Class,
Cascade = {cascadetype. persist, cascadetype. Merge },
Mappedby = "course", fetch = fetchtype. Eager

)
Set fetch type to get directly

2. filter all links
If you want to configure transaction processing when using filter, otherwise the session will be read-only and cannot be modified or deleted.

<
Web-app
>


<
Filter
>



<
Filter-name
>
Hibernatefilter
</
Filter-name
>



<
Filter-class
>


Org. springframework. Orm. hibernate. Support. opensessioninviewfilter


</
Filter-class
>



</
Filter
>


<
Filter-Mapping
>



<
Filter-name
>
Hibernatefilter
</
Filter-name
>



<
URL-Pattern
>
*. Do
</
URL-Pattern
>



</
Filter-Mapping
>


</
Web-app
>
Failed to lazily initialize a collection of Role: xxxxxx, no session or session was closed example: failed to lazily initialize a collection of Role: COM. GTC. wzgl. model. user. roles, no session or session was closed. This exception generally means that the instance of the object fails during many-to-one Operations (and lazy = "false, most of the situations are: 1. carelessness leads to errors in the instance object class name. 2. logical errors. For example, a physical object has been passed in before, then, when calling the method of the object involves one-to-many cases, but the session has been closed, so one-to-many operations cannot be performed at all. 3. Design to span: for example, multiple object objects are directly or indirectly associated. For example, there are four entities: ad information, AD, ad q & A, and advertisers: the relationship between them is: Advertisers 1: N ad ads 1: N ad Q & A advertisers 1: n. The information of advertisers is not directly related to the information of advertisements and advertisers. But when I want to add an advertisement, I must take the entity of the advertisement as a condition. Therefore, the information of advertisers may be used indirectly. See my operations below: AD, subject ad Ad = new ad ();
Ad. setadprod (adform. getadprod ());
Ad. setindustry (industry );
Ad. setadpicture (pagefile. getfilename ());
Ad. setadflack (adform. getadflack ());
Ad. setaddv (dvfile. getfilename ());
Ad. setadcontent (adform. getadcontent ());
Ad. setgray (Gray );
Ad. setaddate (new date ());
Ad. setonlinetime (New Long (0); // enter the basic information of the advertisement. The important thing is to look at the following sentence, here, my idea is that subjectformlist is a dynamic submission form, which contains several ad Q & A questions. I turn these questions into a set and use them as an attribute of AD. Set <subject> subjectset = getsubjectset (subjectformlist, AD );
Ad. setsubjects (subjectset); // then submit. makepersistent is an encapsulated method and its purpose is to save. Addao is a Dao, which contains adus. Addao. makepersistent (AD); it seems logical, as long as we add cascade updates to the subject in the ad ing, this operation can be completed. But in fact, unexpected problems will occur. Let's take a look at the getsubjectset () content: Public set getsubjectset (list <subjectform> subjectlist, ad Ad)
{
Set <subject> set = new hashset <subject> (0 );
Subject subject;

For (iterator <subjectform> it = subjectlist. iterator (); it. hasnext ();)
{
Subject = new subject ();
Subjectform Sf = it. Next ();
Subject. setsucontent (SF. getsucontent ());
Subject. setsuoption (SF. getsuoption ());
Subject. setsuresult (arrays. deeptostring (SF. getsuresult ()));
Subject. setsuype (string. valueof (SF. getsusuype ()));
Subject. setad (AD );
Set. Add (subject );
}


Return set;

} We set a breakpoint on this method and then track it. Then you will find that the breakpoint will only appear after set. Add (subject ).
Failed to lazily initialize a collection of Role: XXXXXXXX no session or
Session was closed: this exception occurs because of the advertisement information of the advertisers.
Gray. Messages. Is it hard to understand? This is also a problem with the lazy mechanism of hibernate. Nothing is perfect. Then how should we deal with such problems. Yes
Many people think that we add lazy = "false" to the advertisers' implicit injection of information. In this way, the gray operation will associate messages and submit data during query. But you will find that
Org. hibernate. lazyinitializationexception: illegal access
This exception occurs in loading collection. Switching lazy = "false" is not recommended. It will reduce your query efficiency. The best solution to this situation is not to be lazy. When performing operations on an object, you should use the DAO of that object, that is, there should be two hql statements. Modify getsubjectset () as follows: public void getsubjectset (list <subjectform> subjectlist, ad Ad)
{
Set <subject> set = new hashset <subject> (0 );
Subjectdao = daofactory. getdao (subjectdao. Class );


For (iterator <subjectform> it = subjectlist. iterator (); it. hasnext ();)
{
Subject subject = new subject ();
Subjectform Sf = it. Next ();
Subject. setsucontent (SF. getsucontent ());
Subject. setsuoption (SF. getsuoption ());
Subject. setsuresult (arrays. deeptostring (SF. getsuresult ()));
Subject. setsuype (string. valueof (SF. getsusuype ()));
Subject. setad (AD );
Subjectdao. makepersistent (subject );
// Set. Add (subject );
}

} // Traverse all the subject items and add them to the database one by one. In this way, there will be no problems. 1. opensessioninview mode: The following two methods are available: 1st are combined with spring, and 2nd are in the interceptor spring + hibernate. If set ing is used, lazy = "true ", when the Po is uploaded to the view layer, the uninitialized session is closed. You can only initialize the parent in Dao. getchilds (). size ();
Spring provides open session in view to solve this problem in two ways.
1. interceptor <! -- </Span> <span style = "color:
RGB (0,128, 0) ">=========== opensession in view Pattern
=================</Span> <span style = "color:
RGB (0,128, 0) "> -->



<
Bean
ID
= "Opensessioninviewinterceptor"


Class

= "Org. springframework. Orm. hibernate3.support. opensessioninviewinterceptor"
>




<
Property
Name
= "Sessionfactory"
Ref
= "Sessionfactory"
/>




</
Bean
>



<
Bean
ID
= "Urlmapping"
Class
= "Org. springframework. Web. servlet. handler. simpleurlhandlermapping"
>




<
Property
Name
= "Interceptors"
Ref
= "Opensessioninviewinterceptor"
/>




<
Property
Name
= "Mappings"
>




<
Props

>


......

</
Props
>




</
Property
>




</
Bean
>
2. Filter <
Web-app
>


<
Filter
>



<
Filter-name
>
Hibernatefilter
</
Filter-name
>



<
Filter-class
>


Org. springframework. Orm. hibernate. Support. opensessioninviewfilter


</
Filter-class
>



</
Filter
>


<
Filter-Mapping
>



<
Filter-name
>
Hibernatefilter
</
Filter-name
>



<
URL-Pattern
>
*. Do
</
URL-Pattern
>



</
Filter-Mapping
>


</
Web-app
>

2nd solutions: hibernate. initialize () forces to load the correlated object. Today, we encounter the error "failed to lazily initialize a collection of Role: No session or session was closed". We tried to find several solutions: 1. Change lazy = true to lazy = false for the one-to-many columns. 2. If XXX is used for queries. load (class, ID) is changed to XXX, get (class, ID)
3. Add <filter> to the Web. xml file.
<Filter-Name> hibernatefilter </filter-Name>
<Filter-class> org. springframework. Orm. hibernate3.support. opensessioninviewfilter </filter-class> <init-param>
<Param-Name> singlesession </param-Name>
<Param-value> false </param-value>
</Init-param> <! -- This --
<Init-param> must be added. Otherwise, it is likely to report
Error: org. springframework. Dao. invaliddataaccessapiusageexception: Write
Operations are not allowed in read-only mode (flushmode. Never)-turn
Your session into flushmode. Auto or remove 'readonly' marker from
Transaction Definition
>
</Filter> <filter-mapping>
<Filter-Name> hibernatefilter </filter-Name>
<URL-pattern> *. MMG </url-pattern>
</Filter-mapping>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.