下面列出了怎么用javax.persistence.NonUniqueResultException的API类实例代码及写法,或者点击链接到github查看源代码。
private void handlePersistenceException(PersistenceException e) {
if ( e instanceof NoResultException ) {
return;
}
if ( e instanceof NonUniqueResultException ) {
return;
}
if ( e instanceof LockTimeoutException ) {
return;
}
if ( e instanceof QueryTimeoutException ) {
return;
}
try {
sharedSessionContract.markForRollbackOnly();
}
catch (Exception ne) {
//we do not want the subsequent exception to swallow the original one
log.unableToMarkForRollbackOnPersistenceException( ne );
}
}
@Override
public R getSingleResult() {
final List<R> resultList = getResultList();
if ( resultList == null || resultList.isEmpty() ) {
throw new NoResultException(
String.format(
"Call to stored procedure [%s] returned no results",
getProcedureName()
)
);
}
else if ( resultList.size() > 1 ) {
throw new NonUniqueResultException(
String.format(
"Call to stored procedure [%s] returned multiple results",
getProcedureName()
)
);
}
return resultList.get( 0 );
}
private static String getParentID(Path node, String derivateId)
throws NoResultException, NonUniqueResultException {
Path parentNode = node.getParent();
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRFSNODES> query = cb.createQuery(MCRFSNODES.class);
Root<MCRFSNODES> nodes = query.from(MCRFSNODES.class);
MCRFSNODES fsNode = em.createQuery(query
.where(
cb.equal(nodes.get(MCRFSNODES_.owner), derivateId),
cb.equal(nodes.get(MCRFSNODES_.name), parentNode.getFileName().toString()),
cb.equal(nodes.get(MCRFSNODES_.type), "D")))
.getSingleResult();
LOGGER.debug("Found directory entry for {}", parentNode.getFileName());
em.detach(fsNode);
return fsNode.getId();
}
protected void invokeFrame1(){
jpaTxnManager.beginTransaction();
try {
//SQL1: select CA_NAME, CA_B_ID, CA_C_ID, CA_TAX_ST from CUSTOMER_ACCOUNT where CA_ID = ?
//Hibernate: select customerac0_.CA_ID as CA1_9_, customerac0_.CA_B_ID as CA5_9_, customerac0_.CA_BAL as CA2_9_, customerac0_.CA_NAME as CA3_9_, customerac0_.CA_TAX_ST as CA4_9_, customerac0_.CA_C_ID as CA6_9_ from CUSTOMER_ACCOUNT customerac0_ where customerac0_.CA_ID=? fetch first 2 rows only
//It is not the bug from GemFireXD dialect when you see the fetch first 2 rows only for getSingleResult.
//It is the hibernate implementation to avoid possible OOME if the setMaxResultSet is not called
//and set the default resultset to 2 rows.
customerAccount = (CustomerAccount)entityManager.createQuery(CUSTOMER_ACCOUNT_QUERY).setParameter("caId", toTxnInput.getAcctId()).getSingleResult();
} catch (NoResultException nre) {
toTxnOutput.setStatus(-711);
throw nre;
} catch (NonUniqueResultException nure) {
toTxnOutput.setStatus(-711);
throw nure;
} catch(RuntimeException re) {
//Any JPA related exceptions are RuntimeException, catch, log and rethrow.
throw re;
}
//SQL2: select C_F_NAME, C_L_NAME, C_TIER, C_TAX_ID from CUSTOMER where C_ID = ?
customer = (Customer)customerAccount.getCustomer();
//SQL3: select B_NAME from BROKER where B_ID = ?
//Hibernate: select broker0_.B_ID as B1_2_0_, broker0_.B_COMM_TOTAL as B2_2_0_, broker0_.B_NAME as B3_2_0_, broker0_.B_NUM_TRADES as B4_2_0_, broker0_.B_ST_ID as B5_2_0_ from BROKER broker0_ where broker0_.B_ID=?
broker = (Broker)customerAccount.getBroker();
}
protected void invokeFrame1(){
jpaTxnManager.beginTransaction();
try {
//SQL1: select CA_NAME, CA_B_ID, CA_C_ID, CA_TAX_ST from CUSTOMER_ACCOUNT where CA_ID = ?
//Hibernate: select customerac0_.CA_ID as CA1_9_, customerac0_.CA_B_ID as CA5_9_, customerac0_.CA_BAL as CA2_9_, customerac0_.CA_NAME as CA3_9_, customerac0_.CA_TAX_ST as CA4_9_, customerac0_.CA_C_ID as CA6_9_ from CUSTOMER_ACCOUNT customerac0_ where customerac0_.CA_ID=? fetch first 2 rows only
//It is not the bug from GemFireXD dialect when you see the fetch first 2 rows only for getSingleResult.
//It is the hibernate implementation to avoid possible OOME if the setMaxResultSet is not called
//and set the default resultset to 2 rows.
customerAccount = (CustomerAccount)entityManager.createQuery(CUSTOMER_ACCOUNT_QUERY).setParameter("caId", toTxnInput.getAcctId()).getSingleResult();
} catch (NoResultException nre) {
toTxnOutput.setStatus(-711);
throw nre;
} catch (NonUniqueResultException nure) {
toTxnOutput.setStatus(-711);
throw nure;
} catch(RuntimeException re) {
//Any JPA related exceptions are RuntimeException, catch, log and rethrow.
throw re;
}
//SQL2: select C_F_NAME, C_L_NAME, C_TIER, C_TAX_ID from CUSTOMER where C_ID = ?
customer = (Customer)customerAccount.getCustomer();
//SQL3: select B_NAME from BROKER where B_ID = ?
//Hibernate: select broker0_.B_ID as B1_2_0_, broker0_.B_COMM_TOTAL as B2_2_0_, broker0_.B_NAME as B3_2_0_, broker0_.B_NUM_TRADES as B4_2_0_, broker0_.B_ST_ID as B5_2_0_ from BROKER broker0_ where broker0_.B_ID=?
broker = (Broker)customerAccount.getBroker();
}
@Test(expected = SaaSSystemException.class)
public void testFindHistoryQueryReturnsNonDomainHistoryObject()
throws Exception {
doThrow(new NonUniqueResultException()).when(namedQuery)
.getSingleResult();
doReturn(namedQuery).when(em).createNamedQuery(any(String.class));
doReturn(namedQuery).when(namedQuery).setParameter(any(String.class),
any());
List<Product> resultNoHistoryObject = Arrays
.asList(domObject_withBusinessKey);
doReturn(resultNoHistoryObject).when(namedQuery).getResultList();
try {
dataService.findHistory(domObject_withBusinessKey);
} catch (SaaSSystemException e) {
String msg = e.getMessage();
assertTrue(msg.indexOf("findHistory loaded Non-History Object") > 0);
throw e;
}
}
/**
* Checks if the supplier has been granted the permission to sell the
* technical product - a corresponding marketing permission must exist.
*
* @param technicalProduct
* the permission check is done against this technical product
* @param supplier
* for which the permission check is done
* @param ds
* data service, used to execute sql queries
* @param logger
* if not <code>null</code> a thrown
* <code>ObjectNotFoundException</code> will be logged as warning
* to the system log
* @throws OperationNotPermittedException
* thrown if no or multiple marketing permissions are found.
*/
public static void hasMarketingPermission(
TechnicalProduct technicalProduct, Organization supplier,
DataService ds, Log4jLogger logger)
throws OperationNotPermittedException {
Query query = ds
.createNamedQuery("MarketingPermission.findForSupplierIds");
query.setParameter("tp", technicalProduct);
List<String> searchList = new ArrayList<>();
searchList.add(supplier.getOrganizationId());
query.setParameter("orgIds", searchList);
query.setParameter("refType",
OrganizationReferenceType.TECHNOLOGY_PROVIDER_TO_SUPPLIER);
try {
query.getSingleResult();
} catch (NoResultException | NonUniqueResultException e) {
logAndThrowMarketingPermissionException(logger,
String.valueOf(technicalProduct.getKey()),
supplier.getOrganizationId());
}
}
protected void invokeFrame1(){
jpaTxnManager.beginTransaction();
try {
//SQL1: select CA_NAME, CA_B_ID, CA_C_ID, CA_TAX_ST from CUSTOMER_ACCOUNT where CA_ID = ?
//Hibernate: select customerac0_.CA_ID as CA1_9_, customerac0_.CA_B_ID as CA5_9_, customerac0_.CA_BAL as CA2_9_, customerac0_.CA_NAME as CA3_9_, customerac0_.CA_TAX_ST as CA4_9_, customerac0_.CA_C_ID as CA6_9_ from CUSTOMER_ACCOUNT customerac0_ where customerac0_.CA_ID=? fetch first 2 rows only
//It is not the bug from GemFireXD dialect when you see the fetch first 2 rows only for getSingleResult.
//It is the hibernate implementation to avoid possible OOME if the setMaxResultSet is not called
//and set the default resultset to 2 rows.
customerAccount = (CustomerAccount)entityManager.createQuery(CUSTOMER_ACCOUNT_QUERY).setParameter("caId", toTxnInput.getAcctId()).getSingleResult();
} catch (NoResultException nre) {
toTxnOutput.setStatus(-711);
throw nre;
} catch (NonUniqueResultException nure) {
toTxnOutput.setStatus(-711);
throw nure;
} catch(RuntimeException re) {
//Any JPA related exceptions are RuntimeException, catch, log and rethrow.
throw re;
}
//SQL2: select C_F_NAME, C_L_NAME, C_TIER, C_TAX_ID from CUSTOMER where C_ID = ?
customer = (Customer)customerAccount.getCustomer();
//SQL3: select B_NAME from BROKER where B_ID = ?
//Hibernate: select broker0_.B_ID as B1_2_0_, broker0_.B_COMM_TOTAL as B2_2_0_, broker0_.B_NAME as B3_2_0_, broker0_.B_NUM_TRADES as B4_2_0_, broker0_.B_ST_ID as B5_2_0_ from BROKER broker0_ where broker0_.B_ID=?
broker = (Broker)customerAccount.getBroker();
}
protected void invokeFrame1(){
jpaTxnManager.beginTransaction();
try {
//SQL1: select CA_NAME, CA_B_ID, CA_C_ID, CA_TAX_ST from CUSTOMER_ACCOUNT where CA_ID = ?
//Hibernate: select customerac0_.CA_ID as CA1_9_, customerac0_.CA_B_ID as CA5_9_, customerac0_.CA_BAL as CA2_9_, customerac0_.CA_NAME as CA3_9_, customerac0_.CA_TAX_ST as CA4_9_, customerac0_.CA_C_ID as CA6_9_ from CUSTOMER_ACCOUNT customerac0_ where customerac0_.CA_ID=? fetch first 2 rows only
//It is not the bug from GemFireXD dialect when you see the fetch first 2 rows only for getSingleResult.
//It is the hibernate implementation to avoid possible OOME if the setMaxResultSet is not called
//and set the default resultset to 2 rows.
customerAccount = (CustomerAccount)entityManager.createQuery(CUSTOMER_ACCOUNT_QUERY).setParameter("caId", toTxnInput.getAcctId()).getSingleResult();
} catch (NoResultException nre) {
toTxnOutput.setStatus(-711);
throw nre;
} catch (NonUniqueResultException nure) {
toTxnOutput.setStatus(-711);
throw nure;
} catch(RuntimeException re) {
//Any JPA related exceptions are RuntimeException, catch, log and rethrow.
throw re;
}
//SQL2: select C_F_NAME, C_L_NAME, C_TIER, C_TAX_ID from CUSTOMER where C_ID = ?
customer = (Customer)customerAccount.getCustomer();
//SQL3: select B_NAME from BROKER where B_ID = ?
//Hibernate: select broker0_.B_ID as B1_2_0_, broker0_.B_COMM_TOTAL as B2_2_0_, broker0_.B_NAME as B3_2_0_, broker0_.B_NUM_TRADES as B4_2_0_, broker0_.B_ST_ID as B5_2_0_ from BROKER broker0_ where broker0_.B_ID=?
broker = (Broker)customerAccount.getBroker();
}
@Override
public WebResource findByUrl(String url) {
Query query = entityManager.createQuery(
"SELECT wr FROM " +
getEntityClass().getName() + " wr"
+ " left join fetch wr.processResultSet pr"
+ " WHERE wr.url = :url");
query.setParameter("url", url);
try {
return (WebResource) query.getSingleResult();
} catch (NoResultException nre) {
return null;
} catch (NonUniqueResultException nure) {
List<WebResource> queryResult = query.getResultList();
for (WebResource wr : queryResult) {
if (StringUtils.equals(wr.getURL(),url)) {
return wr;
}
}
return null;
}
}
@Override
public WebResource findByAuditAndUrl(Audit audit, String url) {
Query query = entityManager.createQuery(
"SELECT wr FROM " +
getEntityClass().getName() + " wr"
+ " left join fetch wr.processResultSet pr"
+ " WHERE wr.url = :url AND wr.audit = :audit");
query.setParameter("url", url);
query.setParameter("audit", audit);
try {
return (WebResource) query.getSingleResult();
} catch (NoResultException nre) {
return null;
} catch (NonUniqueResultException nure) {
List<WebResource> queryResult = query.getResultList();
for (WebResource wr : queryResult) {
if (StringUtils.equals(wr.getURL(),url)) {
return wr;
}
}
return null;
}
}
@Override
public WebResource findByUrlAndParentWebResource(String url, WebResource webResource) {
Query query = entityManager.createQuery(
"SELECT wr FROM " +
PageImpl.class.getName() + " wr"
+ " WHERE wr.url = :url"
+ " AND wr.parent =:webResource");
query.setParameter("url", url);
query.setParameter("webResource", webResource);
try {
return (WebResource) query.getSingleResult();
} catch (NoResultException nre) {
return null;
} catch (NonUniqueResultException nure) {
List<WebResource> queryResult = query.getResultList();
for (WebResource wr : queryResult) {
if (StringUtils.equals(wr.getURL(),url)) {
return wr;
}
}
return null;
}
}
@Override
public Content find(Audit audit, String uri) {
Query query = entityManager.createQuery("SELECT c FROM "
+ getEntityClass().getName() + " c"
+ " WHERE c.audit = :audit"
+ " AND c.uri = :uri"
+ " AND c.httpStatusCode =:httpStatusCode");
query.setParameter(AUDIT_KEY, audit);
query.setParameter("uri", uri);
query.setParameter(HTTP_STATUS_CODE_KEY, HTTP_STATUS_OK);
try {
return (Content) query.getSingleResult();
} catch (NoResultException nre) {
return null;
} catch (NonUniqueResultException nure) {
List<Content> queryResult = query.getResultList();
for (Content content : queryResult) {
if (StringUtils.equals(content.getURI(),uri)) {
return content;
}
}
return null;
}
}
@Override
public Content find(WebResource page, String uri) {
Query query = entityManager.createQuery("SELECT c FROM "
+ getEntityClass().getName() + " c"
+ " WHERE c.page = :page "
+ " AND c.uri = :uri");
query.setParameter("page", page);
query.setParameter("uri", uri);
try {
return (Content) query.getSingleResult();
} catch (NoResultException nre) {
return null;
} catch (NonUniqueResultException nure) {
List<Content> queryResult = query.getResultList();
for (Content content : queryResult) {
if (StringUtils.equals(content.getURI(),uri)) {
return content;
}
}
return null;
}
}
@Override
public Parameter findDefaultParameter(ParameterElement parameterElement) {
Query query = entityManager.createQuery("SELECT p FROM "
+ getEntityClass().getName() + " p"
+ " WHERE p.isDefaultParameterValue = :isDefault"
+ " AND p.parameterElement = :parameterElement");
query.setParameter("isDefault", true);
query.setParameter("parameterElement", parameterElement);
try {
return (Parameter)query.getSingleResult();
} catch (NoResultException nre) {
return null;
} catch (NonUniqueResultException nure) {
return (Parameter)query.getResultList().iterator().next();
}
}
/**
* Retrieves a single {@link ResourceEntity} by the given attribute and value.
*
* @param attribute
* The attribute of the resource entity to retrieve it by
* @param value
* The value of the attribute to compare it to
* @param clazz
* The concrete resource entity class to retrieve (may also be {@link ResourceEntity})
* @return The matching {@link ResourceEntity}
* @throws ResourceNotFoundException
* If no {@link ResourceEntity} could be found
* @throws OsiamException
* If more than 1 {@link ResourceEntity} was found
*/
public <T extends ResourceEntity, V> T getByAttribute(SingularAttribute<? super T, V> attribute, V value,
Class<T> clazz) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(clazz);
Root<T> resource = cq.from(clazz);
cq.select(resource).where(cb.equal(resource.get(attribute), value));
TypedQuery<T> q = em.createQuery(cq);
try {
return q.getSingleResult();
} catch (NoResultException nre) {
throw new ResourceNotFoundException(String.format("Resource with attribute '%s' set to '%s' not found",
attribute.getName(), value), nre);
} catch (NonUniqueResultException nure) {
throw new OsiamException(String.format("Muliple resources with attribute '%s' set to '%s' found",
attribute.getName(), value), nure);
}
}
/**
* Helper method to check if a given WSDLEndpoint is already stored in the database
*
* @param endpoint to look for
* @return true, if the Endpoint already exists.
*/
private boolean existsWSDLEndpoint(final WSDLEndpoint endpoint) {
TypedQuery<WSDLEndpoint> findQuery =
em.createQuery("SELECT e from WSDLEndpoint e where e.PortType = :portType " +
"and e.csarId = :csarId and e.managingContainer = :managingContainer " +
"and e.serviceTemplateInstanceID = :serviceTemplateInstanceID and e.PlanId = :planId", WSDLEndpoint.class);
findQuery.setParameter("portType", endpoint.getPortType());
findQuery.setParameter("csarId", endpoint.getCsarId());
findQuery.setParameter("managingContainer", endpoint.getManagingContainer());
findQuery.setParameter("serviceTemplateInstanceID", endpoint.getServiceTemplateInstanceID());
findQuery.setParameter("planId", endpoint.getPlanId());
try {
@SuppressWarnings("unused")
WSDLEndpoint dbResult = findQuery.getSingleResult();
return true;
} catch (NoResultException | NonUniqueResultException umm) {
// maybe return true if result is not unique?
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public <T> T find(final Class<T> type, final Object id) {
return doWithExceptionTranslation(new Callable<T>() {
@Override
public T call() {
if (id instanceof CompoundKey) {
QueryResults<T> results = findMatching(type,
QueryByCriteria.Builder.andAttributes(((CompoundKey) id).getKeys()).build());
if (results.getResults().size() > 1) {
throw new NonUniqueResultException("Error Compound Key: " + id + " on class " + type.getName()
+ " returned more than one row.");
}
if (!results.getResults().isEmpty()) {
return results.getResults().get(0);
}
return null;
} else {
return sharedEntityManager.find(type, id);
}
}
});
}
protected RoleBo getRoleBoByName(String namespaceCode, String roleName) {
if (StringUtils.isBlank(namespaceCode)
|| StringUtils.isBlank(roleName)) {
return null;
}
Map<String, Object> criteria = new HashMap<String, Object>(3);
criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode);
criteria.put(KimConstants.UniqueKeyConstants.NAME, roleName);
criteria.put(KRADPropertyConstants.ACTIVE, Boolean.TRUE);
QueryResults<RoleBo> results =
getDataObjectService().findMatching(RoleBo.class, QueryByCriteria.Builder.andAttributes(criteria).build());
if (results.getResults().isEmpty()) {
return null;
} else if (results.getResults().size() > 1) {
throw new NonUniqueResultException("Finding a role by name should return a unique role, "
+ "but encountered multiple. namespaceCode='" + namespaceCode + "', name='" + roleName +"'");
}
return results.getResults().get(0);
}
protected RoleBoLite getRoleBoLiteByName(String namespaceCode, String roleName) {
if (StringUtils.isBlank(namespaceCode)
|| StringUtils.isBlank(roleName)) {
return null;
}
Map<String, Object> criteria = new HashMap<String, Object>(3);
criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode);
criteria.put(KimConstants.UniqueKeyConstants.NAME, roleName);
criteria.put(KRADPropertyConstants.ACTIVE, Boolean.TRUE);
QueryResults<RoleBoLite> results =
getDataObjectService().findMatching(RoleBoLite.class, QueryByCriteria.Builder.andAttributes(criteria).build());
if (results.getResults().isEmpty()) {
return null;
} else if (results.getResults().size() > 1) {
throw new NonUniqueResultException("Finding a role by name should return a unique role, "
+ "but encountered multiple. namespaceCode='" + namespaceCode + "', name='" + roleName +"'");
}
return results.getResults().get(0);
}
public UserPoints getUserPoints(String userId, long campaignId) {
final EntityManager em = emProvider.get();
TypedQuery<UserPoints> query = em.createNamedQuery(DBQueries.GET_USER_POINTS, UserPoints.class);
query.setParameter("userId", userId); //$NON-NLS-1$
query.setParameter("campaignId", campaignId); //$NON-NLS-1$
UserPoints result = null;
try {
result = query.getSingleResult();
} catch (NoResultException x) {
logger.debug("Could not retrieve user points for userId {} from table {}.", userId, "User"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (NonUniqueResultException e) {
throw new IllegalStateException(String.format("More than one entity for userId %s from table User.", userId)); //$NON-NLS-1$
}
return result;
}
public Campaign getByCaseInsensitiveName(String name, User user) {
final EntityManager em = emProvider.get();
try {
final TypedQuery<Campaign> query = em.createNamedQuery(DBQueries.GET_CAMPAIGN_BY_CASE_INSENSITIVE_NAME, Campaign.class);
query.setParameter("name", name);
query.setParameter("owner", user);
return query.getSingleResult();
} catch (NoResultException x) {
logger.warn("Could not retrieve entity {} for userId {} from table {}. Maybe the user doesn't exist yet.", name, user.getUserId(),
"Campaign");
} catch (NonUniqueResultException e) {
throw new IllegalStateException(String.format(
"More than one campaign with name %s for userId %s from table Campaign.", name, user.getUserId())); //$NON-NLS-1$
}
return null;
}
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
EntityNotFoundException entityNotFound = new EntityNotFoundException();
assertSame(JpaObjectRetrievalFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());
NoResultException noResult = new NoResultException();
assertSame(EmptyResultDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());
NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
assertSame(IncorrectResultSizeDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());
OptimisticLockException optimisticLock = new OptimisticLockException();
assertSame(JpaOptimisticLockingFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());
EntityExistsException entityExists = new EntityExistsException("foo");
assertSame(DataIntegrityViolationException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());
TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
assertSame(InvalidDataAccessApiUsageException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());
PersistenceException unknown = new PersistenceException() {
};
assertSame(JpaSystemException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
EntityNotFoundException entityNotFound = new EntityNotFoundException();
assertSame(JpaObjectRetrievalFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());
NoResultException noResult = new NoResultException();
assertSame(EmptyResultDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());
NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
assertSame(IncorrectResultSizeDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());
OptimisticLockException optimisticLock = new OptimisticLockException();
assertSame(JpaOptimisticLockingFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());
EntityExistsException entityExists = new EntityExistsException("foo");
assertSame(DataIntegrityViolationException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());
TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
assertSame(InvalidDataAccessApiUsageException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());
PersistenceException unknown = new PersistenceException() {
};
assertSame(JpaSystemException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
@SuppressWarnings("unchecked")
public <T extends Entity> Optional<T> singleResultOptional() {
Query jpaQuery = createQuery(2);
try (NonThrowingCloseable c = applyFilters()) {
List<T> list = jpaQuery.getResultList();
if (list.size() > 1) {
throw new NonUniqueResultException();
}
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0));
}
}
@Override
public String getResourceTemplate(final String webServerName, final String resourceTemplateName) {
final Query q = entityManager.createNamedQuery(JpaWebServerConfigTemplate.GET_WEBSERVER_TEMPLATE_CONTENT);
q.setParameter("webServerName", webServerName);
q.setParameter("templateName", resourceTemplateName);
try {
return (String) q.getSingleResult();
} catch (NoResultException | NonUniqueResultException e) {
LOGGER.error("Error getting resource template {} for web server {}", resourceTemplateName, webServerName, e);
throw new NonRetrievableResourceTemplateContentException(webServerName, resourceTemplateName, e);
}
}
@Override
public String getResourceTemplateMetaData(String webServerName, String resourceTemplateName) {
final Query q = entityManager.createNamedQuery(JpaWebServerConfigTemplate.GET_WEBSERVER_TEMPLATE_METADATA);
q.setParameter("webServerName", webServerName);
q.setParameter("templateName", resourceTemplateName);
try {
return (String) q.getSingleResult();
} catch (NoResultException | NonUniqueResultException e) {
LOGGER.error("Error getting resource meta data {} for web server {}", resourceTemplateName, webServerName, e);
throw new NonRetrievableResourceTemplateContentException(webServerName, resourceTemplateName, e);
}
}
@Override
public String getResourceTemplate(String appName, String resourceTemplateName, String jvmName, String groupName) {
JpaJvm jpaJvm;
Query jvmQuery = entityManager.createNamedQuery(JpaJvm.QUERY_FIND_JVM_BY_GROUP_AND_JVM_NAME);
jvmQuery.setParameter("jvmName", jvmName);
jvmQuery.setParameter("groupName", groupName);
try {
jpaJvm = (JpaJvm) jvmQuery.getSingleResult();
} catch (NoResultException | NonUniqueResultException e) {
LOGGER.error("Error getting resource template {} for app {} and JVM {} in group {}", resourceTemplateName, appName, jvmName, groupName, e);
throw new NonRetrievableResourceTemplateContentException(appName, resourceTemplateName, e);
}
return getResourceTemplate(appName, resourceTemplateName, jpaJvm);
}
@Override
public String getResourceTemplate(final String appName, final String resourceTemplateName, JpaJvm appJvm) {
final Query q = entityManager.createNamedQuery(JpaApplicationConfigTemplate.GET_APP_TEMPLATE_CONTENT);
q.setParameter("appName", appName);
q.setParameter("templateName", resourceTemplateName);
q.setParameter("templateJvm", appJvm);
try {
return (String) q.getSingleResult();
} catch (NoResultException | NonUniqueResultException e) {
LOGGER.error("Error getting resource template {} for app {} and JVM {}", resourceTemplateName, appName, appJvm, e);
throw new NonRetrievableResourceTemplateContentException(appName, resourceTemplateName, e);
}
}
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
EntityNotFoundException entityNotFound = new EntityNotFoundException();
assertSame(JpaObjectRetrievalFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());
NoResultException noResult = new NoResultException();
assertSame(EmptyResultDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());
NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
assertSame(IncorrectResultSizeDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());
OptimisticLockException optimisticLock = new OptimisticLockException();
assertSame(JpaOptimisticLockingFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());
EntityExistsException entityExists = new EntityExistsException("foo");
assertSame(DataIntegrityViolationException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());
TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
assertSame(InvalidDataAccessApiUsageException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());
PersistenceException unknown = new PersistenceException() {
};
assertSame(JpaSystemException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}