javax.persistence.NonUniqueResultException Java Examples

The following examples show how to use javax.persistence.NonUniqueResultException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContentDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #2
Source File: DataServiceBeanTest.java    From development with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example #3
Source File: ParameterDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@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();
    }
}
 
Example #4
Source File: ResourceDao.java    From osiam with MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #5
Source File: PermissionCheck.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example #6
Source File: JpaTradeOrder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #7
Source File: JpaTradeResult.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: JpaTradeOrder.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #9
Source File: CoreEndpointServiceImpl.java    From container with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #10
Source File: JpaPersistenceProvider.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
  * {@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);
             }
         }
     });
 }
 
Example #11
Source File: MCRIFS2Commands.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #12
Source File: RoleServiceBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: UserPointsDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: JpaTradeResult.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #15
Source File: ProcedureCallImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 );
}
 
Example #16
Source File: ExceptionConverterImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 );
	}
}
 
Example #17
Source File: WebResourceDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #18
Source File: CampaignDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #19
Source File: WebResourceDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #20
Source File: WebResourceDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #21
Source File: RoleServiceBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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);
}
 
Example #22
Source File: ContentDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #23
Source File: QueryHandlerTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Test(expected = NonUniqueResultException.class)
public void should_fail_optinal_query_by_name_with_nonunique()
{
    // given
    final String name = "should_fail_optinal_query_by_name_with_nonunique";
    builder.createSimple(name);
    builder.createSimple(name);

    // when
    repo.findOptionalByName(name);
}
 
Example #24
Source File: CriteriaTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Test(expected = NonUniqueResultException.class)
public void should_fail_with_optional_nonunique_result()
{
    // given
    final String name = "should_fail_with_optional_nonunique_result";
    createSimple(name, 10);
    createSimple(name, 10);

    // when
    repo.queryOptional(name);

}
 
Example #25
Source File: UserDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 5 votes vote down vote up
public User getByUserId(String userId) {
	final EntityManager em = emProvider.get();
	try {
		final TypedQuery<User> query = em.createNamedQuery(DBQueries.GET_USER_BY_USER_ID, User.class);
		query.setParameter("userId", userId); //$NON-NLS-1$
		User user = query.getSingleResult();
		return user;
	} catch (NoResultException x) {
		logger.warn("Could not retrieve entity for userId {} from table {}. Maybe the user doesn't exist yet.", userId, "User"); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (NonUniqueResultException ex) {
		throw new IllegalStateException(String.format("More than one entity for userId %s from table User.", userId), ex); //$NON-NLS-1$
	}

	return null;
}
 
Example #26
Source File: DataAccess.java    From joynr with Apache License 2.0 5 votes vote down vote up
public Optional<GetResult> findGetResultForMessageId(String messageId) {
    Query query = entityManager.createQuery("select gr from GetResult gr where gr.messageId = :messageId");
    query.setParameter("messageId", messageId);
    List<GetResult> resultList = query.getResultList();
    logger.trace("Get result for {}:\n{}", messageId, resultList);
    if (resultList.isEmpty()) {
        return Optional.empty();
    }
    if (resultList.size() > 1) {
        throw new NonUniqueResultException("Several entities found with messageId: " + messageId);
    }
    return Optional.of(resultList.get(0));
}
 
Example #27
Source File: UserDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 5 votes vote down vote up
public User findByEmail(String email) {
	final EntityManager em = emProvider.get();
	try {
		final TypedQuery<User> query = em.createNamedQuery(DBQueries.GET_USER_BY_EMAIL, User.class);
		query.setParameter("email", email); //$NON-NLS-1$
		User user = query.getSingleResult();
		return user;
	} catch (NoResultException x) {
		logger.warn("Could not retrieve user with emial {} from table {}. Maybe the user doesn't exist yet.", email, "User"); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (NonUniqueResultException ex) {
		throw new IllegalStateException(String.format("More than one users with email %s from table User.", email), ex); //$NON-NLS-1$
	}

	return null;
}
 
Example #28
Source File: QueryResultTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Test(expected = NonUniqueResultException.class)
public void should_fail_query_optional_with_nonunique()
{
    // given
    final String name = "should_fail_query_optional_with_nonunique";
    builder.createSimple(name);
    builder.createSimple(name);

    // when
    repo.queryResultWithNamed(name).getOptionalResult();
}
 
Example #29
Source File: PersonRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @see #370
 */
@Test
public void returnsFailureOfOption() {

	people.save(new Person("Dave", "Matthews"));
	people.save(new Person("Carter", "Beauford"));

	Try<Option<Person>> result = people.findByLastnameContaining("e");

	assertThat(result.isFailure()).isTrue();
	assertThat(result.getCause()).isInstanceOf(NonUniqueResultException.class);
}
 
Example #30
Source File: ParameterFamilyDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ParameterFamily findParameterFamilyFromCode(String parameterFamilyCode) {
    Query query = entityManager.createQuery("SELECT pf FROM "
            + getEntityClass().getName() + " pf"
            + " WHERE pf.paramFamilyCode = :parameterFamilyCode");
    query.setParameter("parameterFamilyCode", parameterFamilyCode);
    try {
        return (ParameterFamily) query.getSingleResult();
    } catch (NoResultException nre) {
        return null;
    } catch (NonUniqueResultException nure) {
        return null;
    }
}