微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,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,Boolean.TRUE);

    QueryResults<RoleBoLite> results =
            getDataObjectService().findMatching(RoleBoLite.class,name='" + roleName +"'");
    }

    return results.getResults().get(0);
}
项目: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",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,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,id);
             }
         }
     });
 }
项目:rice    文件RoleServiceBase.java   
protected RoleBo getRoleBoByName(String namespaceCode,name='" + roleName +"'");
    }

    return results.getResults().get(0);
}
项目:rice    文件RoleServiceBase.java   
protected RoleBoLite getRoleBoLiteByName(String 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,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.",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,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,LogMessageIdentifier.ERROR_SUBSCRIPTIONID_NOT_UNIQUE_IN_MODIFIEDENTITY,organizationId);
            throw e;
        }

        subscription = dataManager.getReference(Subscription.class,result.longValue());
    }
    return subscription;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。