Are javax.persistence.Query objects cachable?
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 (Str开发者_如何学Pythoning)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.
No, you cannot. Query
is created by (and references) a particular EntityManager
instance which is:
- Not thread-safe.
- Should not be held onto for prolonged periods of time.
I think ChssPly76 is right. But you should maybe look at NamedQueries. Maybe this is something in the direction your looking.
However, you can make the query String itself class-instantiated. This will save you a nanosecond here and there.
Here's a greatly simplified example (I apologize for any syntax or other errors):
private static final String sqlMyQuery =
"SELECT stu FROM Student stu " +
"WHERE stu.zipCode = ?1 " +
"AND stu.status = ?2";
public static Student getStudentByZipAndStatus(String zip, int status) {
Student student = em.createNativeQuery(sqlMyQuery)
.setParameter(1, zip)
.setParameter(2, status)
.getSingleResult();
return (student);
}
精彩评论