當前位置: 首頁>>代碼示例>>Java>>正文


Java NonUniqueResultException類代碼示例

本文整理匯總了Java中javax.persistence.NonUniqueResultException的典型用法代碼示例。如果您正苦於以下問題:Java NonUniqueResultException類的具體用法?Java NonUniqueResultException怎麽用?Java NonUniqueResultException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


NonUniqueResultException類屬於javax.persistence包,在下文中一共展示了NonUniqueResultException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testFindHistoryQueryReturnsNonDomainHistoryObject

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
@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;
    }
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:20,代碼來源:DataServiceBeanTest.java

示例2: findCode

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
public T findCode(String code) {
    T entity;
    String queryString = "Select c FROM " + entityClass.getSimpleName() + " c where c.code = :code1";
    Query query = entityManager.createQuery(queryString).setParameter("code1", code);
    try {
        entity = (T) query.getSingleResult();
    } catch (NoResultException | NonUniqueResultException e) {
        entity = null;
        LOG.log(Level.WARNING, e.getMessage());
    }
    return entity;
}
 
開發者ID:ISIS2503,項目名稱:ThermalComfortBack,代碼行數:13,代碼來源:Persistencer.java

示例3: findControlledVocabularyValueByDatasetFieldTypeAndStrValue

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
/**
 * @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;
        }
    }
}
 
開發者ID:pengchengluo,項目名稱:Peking-University-Open-Research-Data-Platform,代碼行數:35,代碼來源:DatasetFieldServiceBean.java

示例4: getParentID

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
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();
}
 
開發者ID:MyCoRe-Org,項目名稱:mycore,代碼行數:18,代碼來源:MCRIFS2Commands.java

示例5: setExtItem

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
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);
	}
}
 
開發者ID:williamgrosset,項目名稱:OSCAR-ConCert,代碼行數:19,代碼來源:BillingONExtDao.java

示例6: invokeFrame1

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
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();
}
 
開發者ID:gemxd,項目名稱:gemfirexd-oss,代碼行數:26,代碼來源:JpaTradeOrder.java

示例7: invokeFrame1

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
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();
}
 
開發者ID:gemxd,項目名稱:gemfirexd-oss,代碼行數:26,代碼來源:JpaTradeResult.java

示例8: findUniqueOrNone

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:ddRPB,項目名稱:rpb,代碼行數:21,代碼來源:GenericDao.java

示例9: getSingleResult

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
@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;
}
 
開發者ID:Inspiredsoft,項目名稱:parco,代碼行數:17,代碼來源:BaseService.java

示例10: hasMarketingPermission

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
/**
 * 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());
    }
}
 
開發者ID:servicecatalog,項目名稱:development,代碼行數:40,代碼來源:PermissionCheck.java

示例11: find

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
/**
  * {@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);
             }
         }
     });
 }
 
開發者ID:kuali,項目名稱:kc-rice,代碼行數:27,代碼來源:JpaPersistenceProvider.java

示例12: getRoleBoByName

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
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);
}
 
開發者ID:kuali,項目名稱:kc-rice,代碼行數:23,代碼來源:RoleServiceBase.java

示例13: getRoleBoLiteByName

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
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);
}
 
開發者ID:kuali,項目名稱:kc-rice,代碼行數:23,代碼來源:RoleServiceBase.java

示例14: getByAttribute

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:osiam,項目名稱:osiam,代碼行數:37,代碼來源:ResourceDao.java

示例15: loadByField

import javax.persistence.NonUniqueResultException; //導入依賴的package包/類
/**
 * 按指定的字段的值加載記錄<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);
	}
}
 
開發者ID:GeeQuery,項目名稱:ef-orm,代碼行數:35,代碼來源:Session.java


注:本文中的javax.persistence.NonUniqueResultException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。