how to lazy load collection when using spring-data-jpa, with hibernate, from an console application

后端 未结 3 1439
生来不讨喜
生来不讨喜 2020-12-29 03:20

I have an small console application and I am using spring-data-jpa with hibernate. I really can not figure out how to lazy initialize collections when using spring-data-jpa

3条回答
  •  再見小時候
    2020-12-29 03:46

    However, I found a way. This method is inside my service implementation:

    public Set fetchUserOrders(Long userId) {
        User user = userRepository.findOne(userId);
        Hibernate.initialize(user.getOrders());
        Set orders = user.getOrders();
        return orders;
    }
    

    Note: this is as @zagyi sugested in one of his comments, but also pay attention to the statement: Hibernate.initialize(user.getOrders()); without this the collection still wouldn't be initialized and you will get an error.

提交回复
热议问题