Search in sources :

Example 46 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project mycore by MyCoRe-Org.

the class MCRIFS2Commands method fixDirectoryEntry.

private static void fixDirectoryEntry(File node, String derivate_id, String storage_base, boolean check_only) {
    String name = node.getName();
    LOGGER.debug("fixDirectoryEntry : name = {}", name);
    Session session = MCRHIBConnection.instance().getSession();
    Transaction tx = session.getTransaction();
    if (tx.getStatus().isNotOneOf(TransactionStatus.ACTIVE)) {
        tx.begin();
    }
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<MCRFSNODES> query = cb.createQuery(MCRFSNODES.class);
    Root<MCRFSNODES> nodes = query.from(MCRFSNODES.class);
    try {
        em.detach(em.createQuery(query.where(cb.equal(nodes.get(MCRFSNODES_.owner), derivate_id), cb.equal(nodes.get(MCRFSNODES_.name), name), cb.equal(nodes.get(MCRFSNODES_.type), "D"))).getSingleResult());
        LOGGER.debug("Found directory entry for {}", name);
        return;
    } catch (NoResultException e) {
        LOGGER.error("Can't find directory entry for {}", name);
        if (check_only)
            return;
    } catch (NonUniqueResultException e) {
        LOGGER.error("Non unique directory entry for {}", name);
        return;
    } catch (Exception e) {
        e.printStackTrace();
    }
    // fix entry
    LOGGER.info("Fix entry for directory {}", name);
    MCRFileMetadataManager fmmgr = MCRFileMetadataManager.instance();
    String id = fmmgr.createNodeID();
    String pid = null;
    try {
        pid = getParentID(node, derivate_id);
    } catch (NoResultException e1) {
        if (!derivate_id.equals(name)) {
            LOGGER.error("Can't find parent id for directory {}", name);
            return;
        }
    } catch (NonUniqueResultException e1) {
        LOGGER.error("The directory entry for {} and {} is not unique!", derivate_id, node.getParentFile().getName());
        return;
    }
    try {
        MCRFSNODES mcrfsnodes = new MCRFSNODES();
        mcrfsnodes.setId(id);
        mcrfsnodes.setPid(pid);
        mcrfsnodes.setType("D");
        mcrfsnodes.setOwner(derivate_id);
        mcrfsnodes.setName(node.getName());
        mcrfsnodes.setDate(new Date(node.lastModified()));
        em.persist(mcrfsnodes);
        tx.commit();
        LOGGER.debug("Entry {} fixed.", name);
    } catch (HibernateException he) {
        if (tx != null) {
            tx.rollback();
        }
        he.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) NonUniqueResultException(javax.persistence.NonUniqueResultException) HibernateException(org.hibernate.HibernateException) NoResultException(javax.persistence.NoResultException) MCRFSNODES(org.mycore.backend.hibernate.tables.MCRFSNODES) NoResultException(javax.persistence.NoResultException) MCRException(org.mycore.common.MCRException) NonUniqueResultException(javax.persistence.NonUniqueResultException) IOException(java.io.IOException) PersistenceException(javax.persistence.PersistenceException) HibernateException(org.hibernate.HibernateException) MCRFileMetadataManager(org.mycore.datamodel.ifs.MCRFileMetadataManager) Date(java.util.Date) EntityManager(javax.persistence.EntityManager) Transaction(org.hibernate.Transaction) Session(org.hibernate.Session) MCRSession(org.mycore.common.MCRSession)

Example 47 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project ORCID-Source by ORCID.

the class OrcidPropsDaoImpl method exists.

/**
 * Checks if the given key exists in the OrcidPropsEntity table.
 *
 * @param key
 * @return true if the key exists on the OrcidPropsEntity table
 * @throws NonUniqueResultException
 *             if there are more than one row with the same key name
 */
@Override
public boolean exists(String key) throws NonUniqueResultException {
    Assert.hasText(key, "Cannot look for empty keys");
    Query query = entityManager.createQuery("FROM OrcidPropsEntity WHERE key=:key");
    query.setParameter("key", key);
    try {
        query.getSingleResult();
    } catch (NoResultException nre) {
        return false;
    } catch (NonUniqueResultException nure) {
        throw nure;
    }
    return true;
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) Query(javax.persistence.Query) NoResultException(javax.persistence.NoResultException)

Example 48 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project invesdwin-context-persistence by subes.

the class SimpleTestService method getByName.

public SimpleTestEntity getByName(final String name) {
    final SimpleTestEntity example = new SimpleTestEntity();
    example.setName(name);
    final List<SimpleTestEntity> l = dao.findAll(example);
    if (l.size() == 0) {
        return null;
    } else if (l.size() > 1) {
        throw new NonUniqueResultException(String.valueOf(l.size()));
    } else {
        return l.get(0);
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException)

Example 49 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project microservices by pwillhan.

the class CreateExecuteQueries method executeQueries.

@Test
public void executeQueries() throws Exception {
    TestDataCategoriesItems testData = storeTestData();
    Long ITEM_ID = testData.items.getFirstId();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            // Get a list
            Query query = em.createQuery("select i from Item i");
            List<Item> items = query.getResultList();
            assertEquals(items.size(), 3);
        }
        {
            // Get a list of scalar values
            Query query = em.createQuery("select i.name from Item i");
            List<String> itemNames = query.getResultList();
            assertEquals(itemNames.size(), 3);
        }
        {
            // Single result
            TypedQuery<Item> query = em.createQuery("select i from Item i where i.id = :id", Item.class).setParameter("id", ITEM_ID);
            Item item = query.getSingleResult();
            assertEquals(item.getId(), ITEM_ID);
        }
        {
            // Single scalar result
            TypedQuery<String> query = em.createQuery("select i.name from Item i where i.id = :id", String.class).setParameter("id", ITEM_ID);
            String itemName = query.getSingleResult();
            assertEquals(em.find(Item.class, ITEM_ID).getName(), itemName);
        }
        {
            // No (single) result
            boolean gotException = false;
            try {
                TypedQuery<Item> query = em.createQuery("select i from Item i where i.id = :id", Item.class).setParameter("id", 1234l);
                Item item = query.getSingleResult();
            // ...
            } catch (NoResultException ex) {
                // ...
                gotException = true;
            }
            assertTrue(gotException);
        }
        {
            // Not a unique result
            boolean gotException = false;
            try {
                Query query = em.createQuery("select i from Item i where name like '%a%'");
                Item item = (Item) query.getSingleResult();
            // ...
            } catch (NonUniqueResultException ex) {
                // ...
                gotException = true;
            }
            assertTrue(gotException);
        }
        {
            // Scrolling with a database cursor
            Session session = em.unwrap(Session.class);
            org.hibernate.Query query = session.createQuery("select i from Item i order by i.id asc");
            org.hibernate.ScrollableResults cursor = query.scroll(org.hibernate.ScrollMode.SCROLL_INSENSITIVE);
            // Jump to third result row
            cursor.setRowNumber(2);
            // Get first "column"
            Item item = (Item) cursor.get(0);
            // Required!
            cursor.close();
            assertEquals(item.getName(), "Baz");
        }
        {
            // Iterating through a result
            Session session = em.unwrap(Session.class);
            org.hibernate.Query query = session.createQuery("select i from Item i");
            int count = 0;
            // select ID from ITEM
            Iterator<Item> it = query.iterate();
            while (it.hasNext()) {
                // select * from ITEM where ID = ?
                Item next = it.next();
                // ...
                count++;
            }
            // Iterator must be closed, either when the Session
            // is closed or manually:
            Hibernate.close(it);
            assertEquals(count, 3);
        }
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) NonUniqueResultException(javax.persistence.NonUniqueResultException) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query) TypedQuery(javax.persistence.TypedQuery) NoResultException(javax.persistence.NoResultException) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) Iterator(java.util.Iterator) List(java.util.List) Session(org.hibernate.Session) Test(org.testng.annotations.Test)

Example 50 with NonUniqueResultException

use of javax.persistence.NonUniqueResultException in project rubia-forums by flashboss.

the class ForumsModuleImpl method uniqueElement.

static <T> T uniqueElement(List<T> list) throws NonUniqueResultException {
    int size = list.size();
    if (size == 0)
        return null;
    T first = list.get(0);
    for (int i = 1; i < size; i++) {
        if (list.get(i) != first) {
            throw new NonUniqueResultException(list.size() + "");
        }
    }
    return first;
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) MODE_POST(it.vige.rubia.util.NotificationEngine.MODE_POST)

Aggregations

NonUniqueResultException (javax.persistence.NonUniqueResultException)65 NoResultException (javax.persistence.NoResultException)54 Query (javax.persistence.Query)29 EntityManager (javax.persistence.EntityManager)11 List (java.util.List)7 PersistenceException (javax.persistence.PersistenceException)6 Collection (java.util.Collection)5 QueryBuilder (org.meveo.commons.utils.QueryBuilder)5 IOException (java.io.IOException)4 Date (java.util.Date)4 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 EntityExistsException (javax.persistence.EntityExistsException)3 EntityNotFoundException (javax.persistence.EntityNotFoundException)3 OptimisticLockException (javax.persistence.OptimisticLockException)3 TransactionRequiredException (javax.persistence.TransactionRequiredException)3 TypedQuery (javax.persistence.TypedQuery)3 WebResource (org.asqatasun.entity.subject.WebResource)3 HibernateException (org.hibernate.HibernateException)3