How to resolve LazyInitializationException in Spring Data JPA?

后端 未结 6 1564

I have to classes that have a one-to-many-relation. When I try to access the lazily loaded collection I get the LazyInitializationException. I searching the web

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 11:40

    For those who have not the possibility to use JPA 2.1 but want to keep the possibility to return a entity in their controller (and not a String/JsonNode/byte[]/void with write in response):

    there is still the possibility to build a DTO in the transaction, that will be returned by the controller.

    @RestController
    @RequestMapping(value = FooController.API, produces = MediaType.APPLICATION_JSON_VALUE)
    class FooController{
    
        static final String API = "/api/foo";
    
        private final FooService fooService;
    
        @Autowired
        FooController(FooService fooService) {
            this.fooService= fooService;
        }
    
        @RequestMapping(method = GET)
        @Transactional(readOnly = true)
        public FooResponseDto getFoo() {
            Foo foo = fooService.get();
            return new FooResponseDto(foo);
        }
    }
    

提交回复
热议问题