Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

persistence - Is there a way to change the JPA fetch type on a method?

Is there a way to change the JPA fetch type on a single method without editing the entity object?

I have a shared ORM layer consisting of JPA entity classes. This ORM layer is accessed by two DAO layers. One DAO needs lazy fetching, as it is for my web application, the other needs eager fetching, as I need it to be threadsafe.

Here is an example method from my threadsafe DAO,

@PersistenceContext(unitName = "PersistenceUnit", type = PersistenceContextType.TRANSACTION)
private EntityManager em;

public ErrorCode findErrorCodeById(short id) {
    return (ErrorCode) em.createNamedQuery("ErrorCode.findById").
            setParameter("id", id).getSingleResult();
}

How would I make this method (or entire class) use eager fetching?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I assume that your entity associations (@OneToOne, @OneToMany, @ManyToOne) are fechted lazy (FetchType.Lazy)

Then I can think of two ways:

A. write two jpa query one which fetch the association of the lazy (thats the default way for hibernate) and a second query which explicit force eager loading of association (see "fetch" keyword in query).

        Query q = HibernateUtil.getSessionFactory().getCurrentSession()
                .createQuery("select c from Category as c" +
                        " left join fetch c.categorizedItems as ci" +
                        " join fetch ci.item as i");


B. use Hibernate.initialize(entity) to force eager loading of lazy relations of an entity after you have retrieved it (e.g. through finder ...)

ErrorCode lazyCode = findErrorCodeById(1);
// eager load associations
Hibernate.initialize(lazyCode);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...