Example usage for org.hibernate NonUniqueResultException NonUniqueResultException

List of usage examples for org.hibernate NonUniqueResultException NonUniqueResultException

Introduction

In this page you can find the example usage for org.hibernate NonUniqueResultException NonUniqueResultException.

Prototype

public NonUniqueResultException(int resultCount) 

Source Link

Document

Constructs a NonUniqueResultException.

Usage

From source file:net.kamhon.ieagle.dao.HibernateDao.java

License:Apache License

@Override
public T findUnique(T t) {
    List<T> results = findByExample(t);

    if (CollectionUtil.isEmpty(results))
        return null;
    else if (results.size() > 1)
        throw new NonUniqueResultException(results.size());
    else//ww w .j a v  a  2s.c  o  m
        return results.get(0);
}

From source file:org.andromda.timetracker.domain.TaskDaoBase.java

/**
 * {@inheritDoc}//from  w w  w. java 2 s.  c om
 */
@Override
public Task searchUniqueName(final String name) {
    final Search search = new Search(
            new SearchParameter[] { new SearchParameter("name", name, SearchParameter.EQUAL_COMPARATOR) });

    final Set<Task> searchResult = this.search(search);
    switch (searchResult.size()) {
    case 0:
        return null;
    case 1:
        return searchResult.iterator().next();
    default:
        throw new NonUniqueResultException(searchResult.size());
    }
}

From source file:org.andromda.timetracker.domain.TimeAllocationDaoBase.java

/**
 * {@inheritDoc}/*www. j  a  va  2s . c om*/
 */
@Override
public TimeAllocation searchUniqueTimePeriod(final TimePeriod timePeriod) {
    final Search search = new Search(new SearchParameter[] {
            new SearchParameter("timePeriod", timePeriod, SearchParameter.EQUAL_COMPARATOR) });

    final Set<TimeAllocation> searchResult = this.search(search);
    switch (searchResult.size()) {
    case 0:
        return null;
    case 1:
        return searchResult.iterator().next();
    default:
        throw new NonUniqueResultException(searchResult.size());
    }
}

From source file:org.andromda.timetracker.domain.UserDaoBase.java

/**
 * {@inheritDoc}// w ww.  j  a  v  a 2  s  .  c om
 */
@Override
public User searchUniqueUsername(final String username) {
    final Search search = new Search(new SearchParameter[] {
            new SearchParameter("username", username, SearchParameter.EQUAL_COMPARATOR) });

    final Set<User> searchResult = this.search(search);
    switch (searchResult.size()) {
    case 0:
        return null;
    case 1:
        return searchResult.iterator().next();
    default:
        throw new NonUniqueResultException(searchResult.size());
    }
}

From source file:org.andromda.timetracker.domain.UserDaoBase.java

/**
 * {@inheritDoc}/* www  .jav a  2 s .  c om*/
 */
@Override
public User searchUniqueEmail(final String email) {
    final Search search = new Search(
            new SearchParameter[] { new SearchParameter("email", email, SearchParameter.EQUAL_COMPARATOR) });

    final Set<User> searchResult = this.search(search);
    switch (searchResult.size()) {
    case 0:
        return null;
    case 1:
        return searchResult.iterator().next();
    default:
        throw new NonUniqueResultException(searchResult.size());
    }
}

From source file:org.beanfuse.query.hibernate.HibernateQuerySupport.java

License:Open Source License

static Object uniqueElement(final List list) {
    final int size = list.size();
    if (size == 0) {
        return null;
    }//w  w w  .jav  a  2  s. co m
    final Object first = list.get(0);
    for (int i = 1; i < size; i++) {
        if (list.get(i) != first) {
            throw new NonUniqueResultException(list.size());
        }
    }
    return first;
}

From source file:org.brushingbits.jnap.persistence.hibernate.Dao.java

License:Apache License

/**
 * /*w  ww. ja v  a2  s .c o m*/
 * @param result
 * @return
 * @throws QueryException
 */
protected E handleUniqueResult(List<E> result) throws QueryException {
    E uniqueResult = null;
    if (result != null && result.size() > 0) {
        if (result.size() == 1) {
            uniqueResult = result.get(0);
        } else {
            throw new NonUniqueResultException(result.size());
        }
    }
    return uniqueResult;
}

From source file:org.ikasan.connector.base.command.HibernateTransactionalResourceCommandDAO.java

License:BSD License

public XidImpl find(Xid xid) throws TransactionalResourceCommandPersistenceException {
    long startTime = System.currentTimeMillis();
    logger.debug("looking for Xid matching [" + xid + "]"); //$NON-NLS-1$//$NON-NLS-2$
    XidImpl result = null;//from   w w w.j  a  v a 2 s. c om
    Session session = null;
    try {
        session = startSession();
        Query query = session.createQuery(FIND_XID_BY_XID);
        String globalTransactionId = HexConverter.byteArrayToHex(xid.getGlobalTransactionId());
        String branchQualifier = HexConverter.byteArrayToHex(xid.getBranchQualifier());
        query.setParameter(GLOBAL_TRANSACTION_ID_PARAMETER, globalTransactionId);
        query.setParameter(BRANCH_TRANSACTION_ID_PARAMETER, branchQualifier);
        List<XidImpl> xids = query.list();
        if (xids.size() > 1) {
            Iterator<XidImpl> xidIterator = xids.iterator();
            while (xidIterator.hasNext()) {
                XidImpl xidImpl = xidIterator.next();
                logger.debug("found non unique XidImpl [" + xidImpl + "]"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            throw new NonUniqueResultException(xids.size());
        } else if (xids.size() == 1) {
            result = xids.get(0);
        }
        session.getTransaction().commit();
    } catch (HibernateException e) {
        logger.error(e);
        throw new TransactionalResourceCommandPersistenceException(e);
    } finally {
        if (session != null && session.isOpen())
            session.close();
    }
    long endTime = System.currentTimeMillis();
    logger.debug("found [" + xid + "] in [" + (endTime - startTime) + "] ms"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
    return result;
}

From source file:org.sakaiproject.assignment.impl.persistence.AssignmentRepositoryImpl.java

License:Educational Community License

@Override
@Transactional/*w  w w .ja  va  2s .  com*/
@SuppressWarnings("unchecked")
public AssignmentSubmission findSubmissionForUser(String assignmentId, String userId) {
    List<AssignmentSubmission> submissions = sessionFactory.getCurrentSession()
            .createCriteria(AssignmentSubmission.class).add(Restrictions.eq("assignment.id", assignmentId))
            .createAlias("submitters", "s").add(Restrictions.eq("s.submitter", userId)).list();

    switch (submissions.size()) {
    case 0:
        return null;
    case 1:
        return submissions.get(0);
    default:
        log.info("Duplicate submissions detected for assignment {} and user {} attempting to clean",
                assignmentId, userId);
        // when more than 1 was found it is considered a duplicate submission
        // filter out user submissions and those that were submitted
        List<AssignmentSubmission> canRemove = submissions.stream().filter(s -> !s.getGraded()
                && !s.getReturned() && !s.getUserSubmission() && s.getDateSubmitted() == null)
                .collect(Collectors.toList());
        int sizeDiff = submissions.size() - canRemove.size();
        switch (sizeDiff) {
        case 0:
            // we can remove any so lets keep the first one created and remove the rest
            canRemove.sort(Comparator.comparing(AssignmentSubmission::getDateCreated));
            submissions.subList(1, submissions.size()).forEach(s -> deleteSubmission(s.getId()));
            return submissions.get(0);
        case 1:
            submissions.removeAll(canRemove);
            canRemove.forEach(s -> deleteSubmission(s.getId()));
            return submissions.get(0);
        default:
            log.warn(
                    "For assignment {} {} submissions found for user: {}, can only remove {} which is not enough to create a unique submission.",
                    assignmentId, submissions.size(), userId, canRemove.size());
            canRemove.forEach(s -> deleteSubmission(s.getId()));
            throw new NonUniqueResultException(sizeDiff);
        }
    }
}

From source file:org.springframework.orm.hibernate3.HibernateTemplateTests.java

License:Apache License

@Test
public void testExceptions() throws HibernateException {
    SQLException sqlEx = new SQLException("argh", "27");

    final JDBCConnectionException jcex = new JDBCConnectionException("mymsg", sqlEx);
    try {// w  ww. jav  a 2s.c  o m
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw jcex;
            }
        });
        fail("Should have thrown DataAccessResourceFailureException");
    } catch (DataAccessResourceFailureException ex) {
        // expected
        assertEquals(jcex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final SQLGrammarException sgex = new SQLGrammarException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw sgex;
            }
        });
        fail("Should have thrown InvalidDataAccessResourceUsageException");
    } catch (InvalidDataAccessResourceUsageException ex) {
        // expected
        assertEquals(sgex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final LockAcquisitionException laex = new LockAcquisitionException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw laex;
            }
        });
        fail("Should have thrown CannotAcquireLockException");
    } catch (CannotAcquireLockException ex) {
        // expected
        assertEquals(laex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final ConstraintViolationException cvex = new ConstraintViolationException("mymsg", sqlEx, "myconstraint");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw cvex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(cvex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final DataException dex = new DataException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw dex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(dex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final JDBCException jdex = new JDBCException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw jdex;
            }
        });
        fail("Should have thrown HibernateJdbcException");
    } catch (HibernateJdbcException ex) {
        // expected
        assertEquals(jdex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final PropertyValueException pvex = new PropertyValueException("mymsg", "myentity", "myproperty");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw pvex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(pvex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw new PersistentObjectException("");
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
    }

    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw new TransientObjectException("");
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
    }

    final ObjectDeletedException odex = new ObjectDeletedException("msg", "id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw odex;
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
        assertEquals(odex, ex.getCause());
    }

    final QueryException qex = new QueryException("msg");
    qex.setQueryString("query");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw qex;
            }
        });
        fail("Should have thrown InvalidDataAccessResourceUsageException");
    } catch (HibernateQueryException ex) {
        // expected
        assertEquals(qex, ex.getCause());
        assertEquals("query", ex.getQueryString());
    }

    final UnresolvableObjectException uoex = new UnresolvableObjectException("id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw uoex;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(uoex, ex.getCause());
    }

    final ObjectNotFoundException onfe = new ObjectNotFoundException("id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw onfe;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(onfe, ex.getCause());
    }

    final WrongClassException wcex = new WrongClassException("msg", "id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw wcex;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(wcex, ex.getCause());
    }

    final NonUniqueResultException nuex = new NonUniqueResultException(2);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw nuex;
            }
        });
        fail("Should have thrown IncorrectResultSizeDataAccessException");
    } catch (IncorrectResultSizeDataAccessException ex) {
        // expected
        assertEquals(1, ex.getExpectedSize());
        assertEquals(-1, ex.getActualSize());
    }

    final StaleObjectStateException sosex = new StaleObjectStateException(TestBean.class.getName(), "id");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw sosex;
            }
        });
        fail("Should have thrown HibernateOptimisticLockingFailureException");
    } catch (HibernateOptimisticLockingFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(sosex, ex.getCause());
    }

    final StaleStateException ssex = new StaleStateException("msg");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw ssex;
            }
        });
        fail("Should have thrown HibernateOptimisticLockingFailureException");
    } catch (HibernateOptimisticLockingFailureException ex) {
        // expected
        assertNull(ex.getPersistentClassName());
        assertNull(ex.getIdentifier());
        assertEquals(ssex, ex.getCause());
    }

    final HibernateException hex = new HibernateException("msg");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw hex;
            }
        });
        fail("Should have thrown HibernateSystemException");
    } catch (HibernateSystemException ex) {
        // expected
        assertEquals(hex, ex.getCause());
    }
}