Spring data jpa uses lazy operations, springdatajpa

Source: Internet
Author: User

Spring data jpa uses lazy operations, springdatajpa

If a property of the model object uses lazy load, an error will be reported when calling this property. failed to lazily initialize a collection of role cocould not initialize proxy-no Session

 

I checked the circle and got two solutions.

A) discard the lazy operation and change lazy to eager.

However, if I only need one name, But I have pulled all the genealogy, it would be a waste of effort.

B) Use OpenSessionInViewFilter

During configuration, it is unavailable because it requires the bean name of sessionfactory, and Spring Data JPA encapsulates it into entityManagerFactory ......

 

However, this framework should provide the corresponding filter ~

Well, OpenEntityManagerInViewFilter surfaced, not working

I have found a discussion for a long time.

At the end of the page, the poster said: At the moment I give up, I cannot spend more time on this ~~

Someone in the discussion suggested using openEntityManagerInViewInterceptor

So I finally wrote the text.

1. Define bean first

 

1 <bean name = "openEntityManagerInViewInterceptor"

2 class = "org. springframework. orm. jpa. support. OpenEntityManagerInViewInterceptor">
3 <property name = "entityManagerFactory">
4 <ref bean = "entityManagerFactory"/>
5 </property>
6 </bean>

 

2. Add the interceptor bean for the default annotation processing ing to automatically generate sessions

1 <bean
2 class = "org. springframework. web. servlet. mvc. annotation. DefaultAnnotationHandlerMapping">
3 <property name = "interceptors">
4 <list>
5 <ref bean = "openEntityManagerInViewInterceptor"/>
6 </list>
7 </property>
8 </bean>

 

3. Join the transaction

 

When an item is invalid, you need to go to the document to learn about its attributes, so that you are more likely to see your own flaws. You cannot stare at the error and stay in the dead end.

 

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.