views:

65

answers:

2

I'm writing a stateless EJB. I had methods like:

public String getXxx(final String userId) throws ... {
    final Query query = em.createNativeQuery(...);
    query.setParameter(1, userId);
    return (String)query.getSingleResult();
}

Can I cache the Query object instantiating it at load time and using it in a multi-thread environment?

private static final Query query = em.createNativeQuery(...);
public String getXxx(final String userId) throws ... {
    query.setParameter(1, userId);
    return (String)query.getSingleResult();
}

Thanks.

A: 

No, you cannot. Query is created by (and references) a particular EntityManager instance which is:

  1. Not thread-safe.
  2. Should not be held onto for prolonged periods of time.
ChssPly76
A: 

I think ChssPly76 is right. But you should maybe look at NamedAueries. Maybe this is something in the direction your looking.

raffael