> J2EE 6 JPA 2.0 API specifies that EntityManager's
> find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) method
> must return null if the entity does not exist .
> However EclipseLink's implementation throws
> java.lang.IllegalArgumentException even though both arguments are valid
OH! Really? Interesting. I already wrote a utility method to convert the exception to null.
> In my testing I get null back from find when the PK value(s) passed in
> are not found in the database.
> I do get an IllegalArgumentException exception if the attribute type
> passed to find is not exactly the same as the type defined in the class.
Well, I have to confirm Cristi; I replaced the getSingleResult calls with this utility method, using getResultList (throwing an exception is considered heavy, so I decided to go for the list):
* getSingleResult throws an exception if nothing is found.
* @param lQuery
static public Object getSingleResultOrNull(Query lQuery)
java.util.List lList = lQuery.getResultList();
if (lList.size() == 0) return null;
Object o = lList.get(0);
Naturally I can retest, but at the very least this was the case indeed.
On 2010-01-04 17:35, Doug Clarke wrote:
> I am a little confused. There seems to be two issues in this thread.
> 1. em.find will return null for a non existent entity assuming the
> identity type matches that of the mapped entity class.
> 2. query.getSingleResult() will thrown an exception if no entity is
> found executing the query.
Oh my, you are so right. My static find methods used to use getSingleResult; so I was confused and mixed up my find with EM's find.