문제

I have problem with Hibernate lazy loading entities in self created objects within transactional ejb methods.

@Entity
public class SampleEntity {

    ...

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<AnotherEntity> list;

    ...

}

EJB:

@Stateless
public class SampleEjb {

    public void transactionalMethod() {
        SampleEntity entity = //select entity from db

        new SamplePojo().lazyLoad(entity);
    }

}

POJO:

public class SamplePojo {

    public void lazyLoad(SampleEntity entity) {
        //there sometimes i have receiving javax.persistence.TransactionRequiredException
        entity.getList().size();
    }    

}

Interesting is, that problem sometimes occures, sometimes not. First time when I encountered that on my project, I work it out by injecting SamplePojo to my EJB (was thinking EJB transactions aren't injecting to self-created objects). But now i realized that there are other place in my project similar to one I posted here, and transactions are injected and code works well.

Should transaction scope be included to user created objects in EJB methods? Is it random situation that my code with entity lazy loading works? Has anyone met with this problem before?

도움이 되었습니까?

해결책

Transactions aren't injected into objects. A transaction is attached to the current thread (using a ThreadLocal variable). As soon as a thread starts a transaction, every code running in this thread executes in the context of this transaction, whatever objects you might use, until the transaction ends (or a new one is started).

Side note: your lazyLoad() method doesn't load anything. You would have to call a method on the lazy list returned by getList() to load it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top