users@glassfish.java.net

LazyLoad: EntityListeners and EntityManagers

From: <glassfish_at_javadesktop.org>
Date: Tue, 25 Sep 2007 11:09:07 PDT

Hi all,

I have two classes a Fund which has several Prices (historic data over the last few years).
I also use these objects (in detached mode) as data transfer objects (in the presentation layer).
Most of the time the whole historic data is not needed but instead only the current price (the last entry in the
list of prices) is used.

Thus, it is essential to lazily load the prices list. But, I have a problem to automatically load the currentPrice (I can't get the EntityManager in the FundListener). I tried something like this:

@Entity
@EntityListeners({FundListener.class})
@NamedQuery(name = "findCurrentPrice", query = "select max(p.date) from Price p where p.isin = :isin")
public class Fund implements Serializable {

        @Transient
        private Price currentPrice;
        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "fund")
        private List<Price> prices;

}

public class FundListener {

        // this doesn't work
        @PersistenceContext
        private EntityManager manager;

        @PostLoad
        @PostUpdate
        @PostPersist
        public void updateCurrentPrice(Fund fund) {
                Query q = manager.createNamedQuery("findCurrentPrice");
                q.setParameter("isin", fund.getIsin());
                fund.setCurrentPrice((Price) q.getSingleResult());
        }
}

Of course, I could do something like fund.getPrices().get(fund.getPrices().size()-1); (without a Query and an EntityManager) in the updateCurrentPrice method. But when I touch the prices list, I will cause the prices list to be loaded (in contrast to what I want with FetchType.LAZY).

I assume that this is a common problem which may have a standard solution. What am I missing here? How is this problem usually solved?

Any help is greatly appreciated,
Chris

PS: Sorry, I did not find a special JPA forum. So please apologize if I am slightly off-topic. BTW, I am using Glassfish/toplink-essentials.
[Message sent by forum member 'naeger' (naeger)]

http://forums.java.net/jive/thread.jspa?messageID=236999