Java 类javax.persistence.NonUniqueResultException 实例源码
项目:oscm
文件:DataServiceBeanTest.java
@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;
}
}
项目:Peking-University-Open-Research-Data-Platform
文件:DatasetFieldServiceBean.java
/**
* @param dsft The DatasetFieldType in which to look up a
* ControlledVocabularyValue.
* @param strValue String value that may exist in a controlled vocabulary of
* the provided DatasetFieldType.
* @param lenient should we accept alternate spellings for value from mapping table
*
* @return The ControlledVocabularyValue found or null.
*/
public ControlledVocabularyValue findControlledVocabularyValueByDatasetFieldTypeAndStrValue(DatasetFieldType dsft, String strValue, boolean lenient) {
TypedQuery<ControlledVocabularyValue> typedQuery = em.createQuery("SELECT OBJECT(o) FROM ControlledVocabularyValue AS o WHERE o.strValue = :strvalue AND o.datasetFieldType = :dsft", ControlledVocabularyValue.class);
typedQuery.setParameter("strvalue", strValue);
typedQuery.setParameter("dsft", dsft);
try {
ControlledVocabularyValue cvv = typedQuery.getSingleResult();
return cvv;
} catch (NoResultException | NonUniqueResultException ex) {
if (lenient) {
// if the value isn't found, check in the list of alternate values for this datasetFieldType
TypedQuery<ControlledVocabAlternate> alternateQuery = em.createQuery("SELECT OBJECT(o) FROM ControlledVocabAlternate as o WHERE o.strValue = :strvalue AND o.datasetFieldType = :dsft", ControlledVocabAlternate.class);
alternateQuery.setParameter("strvalue", strValue);
alternateQuery.setParameter("dsft", dsft);
try {
ControlledVocabAlternate alternateValue = alternateQuery.getSingleResult();
return alternateValue.getControlledVocabularyValue();
} catch (NoResultException | NonUniqueResultException ex2) {
return null;
}
} else {
return null;
}
}
}
项目:mycore
文件:MCRIFS2Commands.java
private static String getParentID(File node, String derivate_id)
throws NoResultException, NonUniqueResultException {
File parent_node = node.getParentFile();
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), derivate_id),
cb.equal(nodes.get(MCRFSNODES_.name), parent_node.getName()),
cb.equal(nodes.get(MCRFSNODES_.type), "D")))
.getSingleResult();
LOGGER.debug("Found directory entry for {}", parent_node.getName());
em.detach(fsNode);
return fsNode.getId();
}
项目:OSCAR-ConCert
文件:BillingONExtDao.java
public void setExtItem(int billingNo, int demographicNo, String keyVal, String value, Date dateTime, char status) throws NonUniqueResultException {
BillingONExt ext = getClaimExtItem(billingNo, demographicNo, keyVal);
if(ext != null) {
ext.setValue(value);
ext.setDateTime(dateTime);
ext.setStatus(status);
this.merge(ext);
} else {
BillingONExt res = new BillingONExt();
res.setBillingNo(billingNo);
res.setDemographicNo(demographicNo);
res.setKeyVal(keyVal);
res.setValue(value);
res.setDateTime(dateTime);
res.setStatus(status);
this.persist(res);
}
}
项目:gemfirexd-oss
文件:JpaTradeOrder.java
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();
}
项目:gemfirexd-oss
文件:JpaTradeResult.java
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();
}
项目:rpb
文件:GenericDao.java
/**
* We request at most 2, if there's more than one then we throw a {@link NonUniqueResultException}
* @throws NonUniqueResultException
*/
public E findUniqueOrNone(E entity, SearchParameters sp) {
// this code is an optimization to prevent using a count
sp.setFirstResult(0);
sp.setMaxResults(2);
List<E> results = find(entity, sp);
if (results == null || results.isEmpty()) {
return null;
}
if (results.size() > 1) {
throw new NonUniqueResultException("Developper: You expected 1 result but we found more ! sample: " + entity);
}
return results.iterator().next();
}
项目:parco
文件:BaseService.java
@SuppressWarnings("rawtypes")
protected Object getSingleResult( Query query )
{
Object result = null;
List objs = query.getResultList();
if ( objs.size() == 1 )
{
result = objs.get( 0 );
}
else if ( objs.size() > 1 )
{
throw new NonUniqueResultException();
}
return result;
}
项目:development
文件:DataServiceBeanTest.java
@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;
}
}
项目:development
文件:PermissionCheck.java
/**
* 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());
}
}
项目:kc-rice
文件:JpaPersistenceProvider.java
/**
* {@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);
}
}
});
}
项目:kc-rice
文件:RoleServiceBase.java
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);
}
项目:kc-rice
文件:RoleServiceBase.java
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);
}
项目:gemfirexd-oss
文件:JpaTradeOrder.java
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();
}
项目:gemfirexd-oss
文件:JpaTradeResult.java
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();
}
项目:rpb
文件:GenericDao.java
/**
* We request at most 2, if there's more than one then we throw a {@link NonUniqueResultException}
* @throws NonUniqueResultException
*/
public E findUniqueOrNone(E entity, SearchParameters sp) {
// this code is an optimization to prevent using a count
sp.setFirstResult(0);
sp.setMaxResults(2);
List<E> results = find(entity, sp);
if (results == null || results.isEmpty()) {
return null;
}
if (results.size() > 1) {
throw new NonUniqueResultException("Developper: You expected 1 result but we found more ! sample: " + entity);
}
return results.iterator().next();
}
项目:osiam
文件:ResourceDao.java
/**
* 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);
}
}
项目:resource-server
文件:ResourceDao.java
/**
* 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);
}
}
项目:ef-orm
文件:Session.java
/**
* 按指定的字段的值加载记录<br>
* 如果指定的字段不是主键,也只返回第一条数据。
*
* @param field
* 作为查询条件的字段
* @param value
* 要查询的值
* @param unique
* 是否要求结果唯一,为true时如结果不唯一将抛出NonUniqueResultException异常
*
* @return 符合条件的记录
* @throws SQLException
* 如果数据库操作错误,抛出。
* @throws NonUniqueResultException
* 结果不唯一
*/
@SuppressWarnings("unchecked")
public <T> T loadByField(jef.database.Field field, Object value, boolean unique) throws SQLException {
ITableMetadata meta = DbUtils.getTableMeta(field);
Query<?> query = meta.newInstance().getQuery();
query.addCondition(field, Operator.EQUALS, value);
List<?> list = typedSelect(query, null, QueryOption.DEFAULT_MAX1);
if (list.isEmpty()) {
return null;
} else if (list.size() > 1 && unique) {
throw new NonUniqueResultException();
}
if (meta.getType() == EntityType.POJO) {
return (T) ((PojoWrapper) list.get(0)).get();
} else {
return (T) list.get(0);
}
}
项目:karaku
文件:MainInstanceHelper.java
static Object fetchAttribute(final Session session, final String hql,
final MainInstance principal, final Object parent) {
if (!session.isOpen()) {
throw new org.hibernate.LazyInitializationException(
"Session is closed, failed to load Main instance "
+ principal.path());
}
Query query = session.createQuery(hql);
query.setMaxResults(2);
query.setParameter("value", principal.value());
query.setParameter("mainEntity", parent);
List<Object> list = query.list();
if (list == null || list.isEmpty()) {
return null;
}
if (list.size() > 1) {
throw new NonUniqueResultException("Attribute "
+ principal.attribute() + " has more than 1 principal");
}
return list.get(0);
}
项目:sigmah
文件:LayoutGroupHibernateDAO.java
@Override
public LayoutGroup getGroupOfDirectMembershipElementByContact(Integer contactId) {
try {
return (LayoutGroup) em().createNativeQuery("" +
"SELECT lg.* " +
"FROM contact c " +
"JOIN contact_details cd ON (cd.id_contact_model = c.id_contact_model) " +
"JOIN layout_group lg ON (lg.id_layout = cd.id_layout) " +
"JOIN layout_constraint lc ON (lc.id_layout_group = lg.id_layout_group) " +
"JOIN default_contact_flexible_element fe ON (fe.id_flexible_element = lc.id_flexible_element) " +
"WHERE c.id_contact = :contactId " +
"AND fe.type = 'DIRECT_MEMBERSHIP'", LayoutGroup.class)
.setParameter("contactId", contactId)
.getSingleResult();
} catch (NonUniqueResultException e) {
return null;
}
}
项目:rice
文件:JpaPersistenceProvider.java
/**
* {@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);
}
}
});
}
项目:rice
文件:RoleServiceBase.java
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);
}
项目:rice
文件:RoleServiceBase.java
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);
}
项目:Tanaguru
文件:WebResourceDAOImpl.java
@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;
}
}
项目:Tanaguru
文件:WebResourceDAOImpl.java
@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;
}
}
项目:Tanaguru
文件:WebResourceDAOImpl.java
@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;
}
}
项目:Tanaguru
文件:ContentDAOImpl.java
@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;
}
}
项目:Tanaguru
文件:ContentDAOImpl.java
@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;
}
}
项目:Tanaguru
文件:ParameterDAOImpl.java
@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();
}
}
项目:oscar-old
文件:BillingONExtDao.java
public void setExtItem(int billingNo, int demographicNo, String keyVal, String value, Date dateTime, char status) throws NonUniqueResultException {
BillingONExt ext = getClaimExtItem(billingNo, demographicNo, keyVal);
if(ext != null) {
ext.setValue(value);
ext.setDateTime(dateTime);
ext.setStatus(Character.toString(status));
this.merge(ext);
} else {
BillingONExt res = new BillingONExt();
res.setBillingNo(billingNo);
res.setDemographicNo(demographicNo);
res.setKeyVal(keyVal);
res.setValue(value);
res.setDateTime(dateTime);
res.setStatus(Character.toString(status));
this.persist(res);
}
}
项目:gsid
文件:IdentifierMetadataDao.java
/******
* This method is used to load the data of an identifier without prefix.
*
* @param identifier
* unprefixed identifier for which the data has to be loaded.
* @return identifier data in the form of IdentifierMetaData.
* @throws InvalidIdentifierException
* @throws NamingAuthorityConfigurationException
*/
public IdentifierMetadata loadLocalIdentifier(final URI localIdentifier) throws InvalidIdentifierException,
NamingAuthorityConfigurationException {
LOG.debug("The local identifier is " + localIdentifier);
List<IdentifierMetadata> results = getHibernateTemplate().find(
"SELECT md FROM " + domainClass().getName() + " md WHERE md.localIdentifier = ?",
new Object[] { localIdentifier });
IdentifierMetadata result = null;
if (results.size() > 1) {
throw new NonUniqueResultException("Found " + results.size() + " " + domainClass().getName() + " objects.");
}
else if (results.size() == 1) {
result = results.get(0);
}
if (result == null) {
throw new InvalidIdentifierException("Local identifier (" + localIdentifier + ") does not exist");
}
return result;
}
项目:cagrid-core
文件:IdentifierMetadataDao.java
public IdentifierMetadata loadLocalIdentifier( final URI localIdentifier )
throws InvalidIdentifierException, NamingAuthorityConfigurationException {
List<IdentifierMetadata> results = getHibernateTemplate().find(
"SELECT md FROM " + domainClass().getName() + " md WHERE md.localIdentifier = ?",
new Object[]{localIdentifier});
IdentifierMetadata result = null;
if (results.size() > 1) {
throw new NonUniqueResultException("Found " + results.size() + " " + domainClass().getName()
+ " objects.");
} else if (results.size() == 1) {
result = results.get(0);
}
if (result == null) {
throw new InvalidIdentifierException("Local identifier (" + localIdentifier + ") does not exist");
}
return result;
}
项目:cloud-sfsf-benefits-ext
文件:UserPointsDAO.java
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;
}
项目:cloud-sfsf-benefits-ext
文件:CampaignDAO.java
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;
}
项目:oscm
文件:EventServiceBeanIT.java
@Test
public void testRecordEventForInstance() throws Exception {
event = new VOGatheredEvent();
event.setActor(ACTOR);
event.setOccurrenceTime(TIMESTAMP);
event.setEventId(PlatformEventIdentifier.USER_LOGIN_TO_SERVICE);
event.setMultiplier(MULTIPLIER);
event.setUniqueId(UNIQUEID);
evMgmt.recordEventForInstance(technicalProductId, instanceId, event);
GatheredEvent savedEvent = readEvent(ACTOR, TIMESTAMP, SUBSCRIPTION_KEY,
EventType.SERVICE_EVENT);
testSavedEvent(TIMESTAMP, MULTIPLIER, UNIQUEID, savedEvent,
EventType.SERVICE_EVENT);
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
Subscription subscription = Subscriptions.createSubscription(
mgr, customerId, productId, "SUBSCRIPTION_2", supplier);
subscription.setProductInstanceId(instanceId);
return null;
}
});
try {
evMgmt.recordEventForInstance(technicalProductId, instanceId,
event);
Assert.fail("recordEvent() must faile!");
} catch (EJBException e) {
Assert.assertEquals(NonUniqueResultException.class,
e.getCause().getCause().getClass());
}
}
项目:oscm
文件:TechnicalProductImportParser.java
BillingAdapter getDefaultBillingAdapter() {
Query query = dm.createNamedQuery("BillingAdapter.getDefaultAdapter");
try {
BillingAdapter defaultAdapter = (BillingAdapter) query
.getSingleResult();
return defaultAdapter;
} catch (NonUniqueResultException e) {
SaaSSystemException se = new SaaSSystemException(
"More than one default billing adapter were found", e);
logger.logError(Log4jLogger.SYSTEM_LOG, se,
LogMessageIdentifier.ERROR_MULTIPLE_DEFAULT_BILLING_ADAPTER_FOUND);
throw se;
}
}
项目:oscm
文件:PermissionCheckTest.java
@Test(expected = OperationNotPermittedException.class)
public void hasMarketingPermission_NonUniqueResult()
throws OperationNotPermittedException {
TechnicalProduct tpMock = mock(TechnicalProduct.class);
Organization supplierMock = mock(Organization.class);
DataService dsMock = mock(DataService.class);
Query queryMock = mock(Query.class);
when(dsMock.createNamedQuery(anyString())).thenReturn(queryMock);
when(queryMock.getSingleResult()).thenThrow(
new NonUniqueResultException());
PermissionCheck.hasMarketingPermission(tpMock, supplierMock, dsMock,
loggerMock);
}
项目:oscm
文件:DataServiceBeanTest.java
@Test(expected = SaaSSystemException.class)
public void testFindNonUniqueResult() 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());
try {
dataService.find(domObject_withBusinessKey);
} catch (SaaSSystemException e) {
String msg = e.getMessage();
assertTrue(msg.indexOf("Non-Unique Business Key Search for") > 0);
throw e;
}
}
项目:oscm
文件:ModifyAndUpgradeSubscriptionBean.java
/**
* For async modifying subscription, the subscription id may be changed,
* when the provisioning service call
* completeAsyncModifySubscription/abortAsyncModifySubscription, the passed
* parameter subscriptionId is modified ID, and can not be found in
* subscription table. If not found in subscription table, try to get
* subscription key in modifiedentity.
*
* @param subscriptionId
* the subscription id
* @param organizationId
* the organization id
* @return the subscription
* @throws ObjectNotFoundException
* in case the organization or the subscription wasn't found
*/
Subscription findSubscriptionForAsyncCallBack(String subscriptionId,
String organizationId) throws ObjectNotFoundException {
Subscription subscription = null;
try {
subscription = findSubscription(subscriptionId, organizationId);
} catch (ObjectNotFoundException e) {
Long result = null;
try {
result = getSubscriptionDao().findSubscriptionForAsyncCallBack(
subscriptionId, organizationId);
} catch (NoResultException ex) {
LOG.logError(Log4jLogger.SYSTEM_LOG, ex,
LogMessageIdentifier.ERROR_SUBSCRIPTIONID_NOT_EXIST_IN_MODIFIEDENTITY,
subscriptionId, organizationId);
throw e;
} catch (NonUniqueResultException se) {
LOG.logError(Log4jLogger.SYSTEM_LOG, se,
LogMessageIdentifier.ERROR_SUBSCRIPTIONID_NOT_UNIQUE_IN_MODIFIEDENTITY,
subscriptionId, organizationId);
throw e;
}
subscription = dataManager.getReference(Subscription.class,
result.longValue());
}
return subscription;
}