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

后端 未结 3 1452
生来不讨喜
生来不讨喜 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

    One solution can be to make User.orders an eagerly fetched collection by

    @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    private Set orders = new HashSet();
    

    Entity associations are lazily loaded by default. This means that the orders Set is actually just a proxy object that won't get initialized until you invoke a method on it. This is good, because the associated Order objects won't get loaded unless they are needed. However, this can cause problems, if you try to access the uninitialized collection outside of a running transaction.

    If you know that in most of the cases you will need the User's Orders, it makes sense to make the association eagerly fetched. Otherwise you will have to ensure that the collection gets initialized/loaded inside a transaction. The OpenSessionInViewFilter you mentioned makes sure that the transaction stays open during the request processing, that is why you don't have this issue in yout webapp.

    In case you must keep it lazily loaded, try using Spring's TransactionTemplate to wrap the code in your main method:

    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
        ...
        }
    });
    

提交回复
热议问题