LazyInitializationException: could not initialize proxy - no Session

后端 未结 3 716
春和景丽
春和景丽 2020-12-09 21:04

I use spring-data-jpa with spring-boot(v2.0.0.RELEASE), I just wrote a CRUD demo on MySQL, but an exception occurs during runtime, source code as f

相关标签:
3条回答
  • 2020-12-09 21:19

    In the service class please add a setter for entity manager by using the annoattion @PersistenceContext. To be specific, use

     @PersistenceContext(type = PersistenceContextType.EXTENDED)
    

    In this way, you can access lazy property.

    0 讨论(0)
  • 2020-12-09 21:34

    Your test should be like this:

    @RunWith(SpringRunner.class)    
    
    
    @SpringBootTest
    @Transactional    
    
    public class QuestionTesting {   
    
        @Test    
        public void test() {    
    
        }    
    }    
    
    0 讨论(0)
  • 2020-12-09 21:37

    You can add @Transactional annotation to your test method to avoid this exception.

    Method getOne return the 'reference' (proxy) of the entity which properties can be lazy loaded. See it code - it uses getReference method of EntityManager. From it javadoc:

    Get an instance, whose state may be lazily fetched.

    In Spring the implementation of EntityManager is org.hibernate.internal.SessionImpl - so without the Session the Spring can not get this method.

    To have a session you can just create a transaction...

    0 讨论(0)
提交回复
热议问题