Hi,
The spec doesn't provide a means to do what you're looking for, but
OpenJPA does -- you can call OpenJPAPersistence.getEntityManager(o) to
obtain the entity manager for a given object.
Also, it might be useful to use entity callbacks defined in the entity
class itself instead of external listeners, from a programming
standpoint. You can do this by just annotating a method in your Fund
class with @PostLoad etc.
-Patrick
On 9/26/07, Christian Näger <[EMAIL PROTECTED]> wrote:
>
> 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
> --
> View this message in context:
> http://www.nabble.com/EntityManager-in-EntityListener-tf4524285.html#a12907684
> Sent from the OpenJPA Users mailing list archive at Nabble.com.
>
>
--
Patrick Linskey
202 669 5907