Problem
As we do search via primary key, it will show this exception message if JPA does not search any matched data
1: org.apache.openjpa.persistence.NoResultException: The query on candidate type "class gov.fdc.nig.domain.Nigt020" with filter "select t1 from Nigt020 t1, Nigt022 t2 where t2.id.dlvUnit = ?1 and t2.id.taxCd = ?2 and t2.id.dlvYr = ?3 and t2.id.flgTp = ?4 and t2.id.serialNo = ?5 and t2.paraTp <> ?6 and t2.paraTp = t1.paraTp" was configured to have a unique result, but no instance matched the query.
2: at org.apache.openjpa.kernel.QueryImpl.singleResult(QueryImpl.java:1299) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
3: at org.apache.openjpa.kernel.QueryImpl.toResult(QueryImpl.java:1221) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
4: at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:990) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
5: at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:805) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
6: at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:775) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
7: at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:533) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
8: at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:252) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
9: at org.apache.openjpa.persistence.QueryImpl.getSingleResult(QueryImpl.java:317) ~[com.ibm.ws.jpa.jar:1.0.1-SNAPSHOT]
The original approach is to call getSingleResult method:
1: public Object createQueryForSingleResult(String jpql, Object[] params, Dao.PersistenceUnit persistenceUnitName) {
2: EntityManager em = getEntityManager(persistenceUnitName);
3: Query query = em.createQuery(jpql);
4: for (int i = 0; i < params.length; i++) {
5: query.setParameter(i + 1, params[i]);
6: }
7: return query.getSingleResult();
8: }
Solution
Just change to this way, then the exception will not take place again:
1: public Object createQueryForSingleResult(String jpql, Object[] params, Dao.PersistenceUnit persistenceUnitName) {
2: Object result = null;
3: EntityManager em = getEntityManager(persistenceUnitName);
4: Query query = em.createQuery(jpql);
5: for (int i = 0; i < params.length; i++) {
6: query.setParameter(i + 1, params[i]);
7: }
8: List list = query.getResultList();
9: if(!CollectionUtils.isEmpty(list)){
10: result = list.get(0);
11: }
12: return result;
13: }
No comments:
Post a Comment