HHH-10833 - JPA NoResultException and NonUniqueResultException not thrown from getSingleResult.

This commit is contained in:
Chris Cranford 2016-06-11 15:56:36 -05:00
parent ec86d2d446
commit 42f3028dca
2 changed files with 39 additions and 1 deletions

View File

@ -31,6 +31,7 @@ import javax.persistence.CacheRetrieveMode;
import javax.persistence.CacheStoreMode;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.NoResultException;
import javax.persistence.Parameter;
import javax.persistence.TemporalType;
import javax.persistence.TransactionRequiredException;
@ -464,7 +465,7 @@ public abstract class AbstractProducedQuery<R> implements QueryImplementor<R> {
@SuppressWarnings("unchecked")
public QueryImplementor setParameter(String name, Object value) {
if ( value instanceof TypedParameterValue ) {
final TypedParameterValue typedValueWrapper = (TypedParameterValue ) value;
final TypedParameterValue typedValueWrapper = (TypedParameterValue) value;
setParameter( name, typedValueWrapper.getValue(), typedValueWrapper.getType() );
}
else if ( value instanceof Collection ) {
@ -1378,6 +1379,25 @@ public abstract class AbstractProducedQuery<R> implements QueryImplementor<R> {
return uniqueElement( list() );
}
@Override
public R getSingleResult() {
try {
final List<R> list = list();
if ( list.size() == 0 ) {
throw new NoResultException( "No entity found for query" );
}
return uniqueElement( list );
}
catch ( HibernateException e ) {
if ( getProducer().getFactory().getSessionFactoryOptions().isJpaBootstrap() ) {
throw getExceptionConverter().convert( e );
}
else {
throw e;
}
}
}
public static <R> R uniqueElement(List<R> list) throws NonUniqueResultException {
int size = list.size();
if ( size == 0 ) {

View File

@ -15,6 +15,7 @@ import java.util.Map;
import javax.persistence.CacheRetrieveMode;
import javax.persistence.CacheStoreMode;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Parameter;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
@ -41,6 +42,7 @@ import org.junit.Test;
import junit.framework.Assert;
import static junit.framework.Assert.assertNull;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@ -1380,4 +1382,20 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
}
}
@Test
@TestForIssue(jiraKey = "HHH-10833")
public void testGetSingleResultWithNoResultException() {
final EntityManager entityManager = getOrCreateEntityManager();
try {
entityManager.createQuery( "FROM Item WHERE name = 'bozo'" ).getSingleResult();
fail( "Expected NoResultException" );
}
catch ( Exception e ) {
assertTyping( NoResultException.class, e );
}
finally {
entityManager.close();
}
}
}