Im using JPA in my Java ee application. I have a table A mapped to a class A. Now when I query the entity (e.g. by its id) it always returns a different object. Example:
public A getAById(int id) {
A obj = (A) em.createNamedQuery("getAById")
.setParameter("id", id).getSingleResult();
return obj;
}
public void test(){
getAById(1)==getAById(1) //is false
}
Is there a way to tell JPA not to always create new instances when querying from a database but to return an existing object if it hast alreay been queried?
//EDIT
This article helped me a lot:
http://en.wikibooks.org/wiki/Java_Persistence/Caching#Example_JPA_2.0_Cacheable_annotation
JavaEE containers wrap the JPA providers EntityManager in a proxy, so the behavior you see is likely because your container gets a new EM outside of a transaction. Your two getAById(1) calls are going to two different EntityManagers underneath the covers. You can get around this by wrapping them in a single transaction, forcing the container to use the same entity manager for the life of the transaction.