Search in sources :

Example 41 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class OneToManyTest method testUnidirectionalDefault.

@Test
public void testUnidirectionalDefault() throws Exception {
    Session s;
    Transaction tx;
    Trainer trainer = new Trainer();
    trainer.setName("First trainer");
    Tiger regularTiger = new Tiger();
    regularTiger.setName("Regular Tiger");
    Tiger whiteTiger = new Tiger();
    whiteTiger.setName("White Tiger");
    trainer.setTrainedTigers(new HashSet<Tiger>());
    s = openSession();
    tx = s.beginTransaction();
    s.persist(trainer);
    s.persist(regularTiger);
    s.persist(whiteTiger);
    trainer.getTrainedTigers().add(regularTiger);
    trainer.getTrainedTigers().add(whiteTiger);
    tx.commit();
    s.close();
    s = openSession();
    tx = s.beginTransaction();
    trainer = (Trainer) s.get(Trainer.class, trainer.getId());
    assertNotNull(trainer);
    assertNotNull(trainer.getTrainedTigers());
    assertEquals(2, trainer.getTrainedTigers().size());
    tx.rollback();
    s.close();
    s = openSession();
    tx = s.beginTransaction();
    trainer = new Trainer();
    trainer.setName("new trainer");
    trainer.setTrainedTigers(new HashSet<Tiger>());
    trainer.getTrainedTigers().add(whiteTiger);
    try {
        s.persist(trainer);
        tx.commit();
        fail("A one to many should not allow several trainer per Tiger");
    } catch (PersistenceException ce) {
        try {
            assertTyping(ConstraintViolationException.class, ce.getCause());
        // success
        } finally {
            tx.rollback();
        }
    }
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) PersistenceException(javax.persistence.PersistenceException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) Session(org.hibernate.Session) Test(org.junit.Test)

Example 42 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class CriteriaHQLAlignmentTest method testCountReturnValues.

@Test
@SkipForDialect(value = Oracle8iDialect.class, comment = "Cannot count distinct over multiple columns in Oracle")
@SkipForDialect(value = SQLServerDialect.class, comment = "Cannot count distinct over multiple columns in SQL Server")
public void testCountReturnValues() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Human human1 = new Human();
    human1.setName(new Name("John", 'Q', "Public"));
    human1.setNickName("Johnny");
    s.save(human1);
    Human human2 = new Human();
    human2.setName(new Name("John", 'A', "Doe"));
    human2.setNickName("Johnny");
    s.save(human2);
    Human human3 = new Human();
    human3.setName(new Name("John", 'A', "Doe"));
    human3.setNickName("Jack");
    s.save(human3);
    Human human4 = new Human();
    human4.setName(new Name("John", 'A', "Doe"));
    s.save(human4);
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    Long count = (Long) s.createQuery("select count( * ) from Human").uniqueResult();
    assertEquals(4, count.longValue());
    s.clear();
    count = (Long) s.createCriteria(Human.class).setProjection(Projections.rowCount()).uniqueResult();
    assertEquals(4, count.longValue());
    s.clear();
    count = (Long) s.createQuery("select count( nickName ) from Human").uniqueResult();
    assertEquals(3, count.longValue());
    s.clear();
    count = (Long) s.createCriteria(Human.class).setProjection(Projections.count("nickName")).uniqueResult();
    assertEquals(3, count.longValue());
    s.clear();
    count = (Long) s.createQuery("select count( distinct nickName ) from Human").uniqueResult();
    assertEquals(2, count.longValue());
    s.clear();
    count = (Long) s.createCriteria(Human.class).setProjection(Projections.count("nickName").setDistinct()).uniqueResult();
    assertEquals(2, count.longValue());
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    try {
        count = (Long) s.createQuery("select count( distinct name ) from Human").uniqueResult();
        if (!getDialect().supportsTupleDistinctCounts()) {
            fail("expected SQLGrammarException");
        }
        assertEquals(2, count.longValue());
    } catch (SQLGrammarException ex) {
        if (!getDialect().supportsTupleDistinctCounts()) {
        // expected
        } else {
            throw ex;
        }
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    try {
        count = (Long) s.createCriteria(Human.class).setProjection(Projections.count("name").setDistinct()).uniqueResult();
        if (!getDialect().supportsTupleDistinctCounts()) {
            fail("expected SQLGrammarException");
        }
        assertEquals(2, count.longValue());
    } catch (SQLGrammarException ex) {
        if (!getDialect().supportsTupleDistinctCounts()) {
        // expected
        } else {
            throw ex;
        }
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    count = (Long) s.createQuery("select count( distinct name.first ) from Human").uniqueResult();
    assertEquals(1, count.longValue());
    s.clear();
    count = (Long) s.createCriteria(Human.class).setProjection(Projections.count("name.first").setDistinct()).uniqueResult();
    assertEquals(1, count.longValue());
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    try {
        count = (Long) s.createQuery("select count( name ) from Human").uniqueResult();
        if (!getDialect().supportsTupleCounts()) {
            fail("expected SQLGrammarException");
        }
        assertEquals(1, count.longValue());
    } catch (SQLGrammarException ex) {
        if (!getDialect().supportsTupleCounts()) {
        // expected
        } else {
            throw ex;
        }
    } catch (PersistenceException e) {
        SQLGrammarException cause = assertTyping(SQLGrammarException.class, e.getCause());
        if (!getDialect().supportsTupleCounts()) {
        // expected
        } else {
            throw e;
        }
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    try {
        count = (Long) s.createCriteria(Human.class).setProjection(Projections.count("name")).uniqueResult();
        if (!getDialect().supportsTupleCounts()) {
            fail("expected SQLGrammarException");
        }
        assertEquals(1, count.longValue());
    } catch (SQLGrammarException ex) {
        if (!getDialect().supportsTupleCounts()) {
        // expected
        } else {
            throw ex;
        }
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    s.createQuery("delete from Human").executeUpdate();
    t.commit();
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) SQLGrammarException(org.hibernate.exception.SQLGrammarException) PersistenceException(javax.persistence.PersistenceException) Session(org.hibernate.Session) SkipForDialect(org.hibernate.testing.SkipForDialect) Test(org.junit.Test)

Example 43 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class InterceptorTest method testTimeout.

/**
 * Test that setting a transaction timeout will cause an Exception to occur
 * if the transaction timeout is exceeded.
 */
@Test
public void testTimeout() throws Exception {
    final int TIMEOUT = 2;
    final int WAIT = TIMEOUT + 1;
    Session s = openSession();
    // Get the transaction and set the timeout BEFORE calling begin()
    Transaction t = s.getTransaction();
    t.setTimeout(TIMEOUT);
    t.begin();
    // Sleep for an amount of time that exceeds the transaction timeout
    Thread.sleep(WAIT * 1000);
    try {
        // Do something with the transaction and try to commit it
        s.persist(new User("john", "test"));
        t.commit();
        fail("Transaction should have timed out");
    } catch (PersistenceException e) {
        assertTyping(TransactionException.class, e.getCause());
        assertTrue("Transaction failed for the wrong reason.  Expecting transaction timeout, but found [" + e.getCause().getMessage() + "]", e.getCause().getMessage().contains("transaction timeout expired"));
    }
}
Also used : TransactionException(org.hibernate.TransactionException) Transaction(org.hibernate.Transaction) PersistenceException(javax.persistence.PersistenceException) Session(org.hibernate.Session) Test(org.junit.Test)

Example 44 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class NativeSQLQueriesTest method testFailOnNoAddEntityOrScalar.

@Test
@SkipForDialect(H2Dialect.class)
public void testFailOnNoAddEntityOrScalar() {
    // Note: this passes, but for the wrong reason.
    // there is actually an exception thrown, but it is the database
    // throwing a sql exception because the SQL gets passed
    // "un-processed"...
    // 
    // Oddly, H2 accepts this query.
    Session s = openSession();
    s.beginTransaction();
    try {
        String sql = "select {org.*} " + "from organization org";
        s.createSQLQuery(sql).list();
        fail("Should throw an exception since no addEntity nor addScalar has been performed.");
    } catch (PersistenceException pe) {
    // expected behavior
    } finally {
        s.getTransaction().rollback();
        s.close();
    }
}
Also used : PersistenceException(javax.persistence.PersistenceException) Session(org.hibernate.Session) SkipForDialect(org.hibernate.testing.SkipForDialect) Test(org.junit.Test)

Example 45 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class JpaXsdVersionsTest method testInvalidOrm1.

@Test
public void testInvalidOrm1() {
    PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl("invalid-orm1-test", "1.0").addMappingFileName("org/hibernate/test/jpa/xml/versions/invalid-orm-1_0.xml");
    HibernatePersistenceProvider hp = new HibernatePersistenceProvider();
    EntityManagerFactory emf = null;
    try {
        emf = hp.createContainerEntityManagerFactory(pui, Collections.EMPTY_MAP);
        Assert.fail("expecting 'invalid content' error");
    } catch (InvalidMappingException | AnnotationException expected) {
    // expected condition
    } catch (PersistenceException expected) {
    // expected condition
    } finally {
        if (emf != null) {
            emf.close();
        }
    }
}
Also used : InvalidMappingException(org.hibernate.InvalidMappingException) EntityManagerFactory(javax.persistence.EntityManagerFactory) PersistenceException(javax.persistence.PersistenceException) HibernatePersistenceProvider(org.hibernate.jpa.HibernatePersistenceProvider) AnnotationException(org.hibernate.AnnotationException) Test(org.junit.Test)

Aggregations

PersistenceException (javax.persistence.PersistenceException)191 Test (org.junit.Test)73 Session (org.hibernate.Session)57 EntityManager (javax.persistence.EntityManager)39 Transaction (org.hibernate.Transaction)34 EntityTransaction (javax.persistence.EntityTransaction)21 IOException (java.io.IOException)18 Query (javax.persistence.Query)18 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)18 List (java.util.List)16 ArrayList (java.util.ArrayList)14 TypedQuery (javax.persistence.TypedQuery)11 JPAQuery (org.datanucleus.api.jpa.JPAQuery)10 StaleObjectStateException (org.hibernate.StaleObjectStateException)10 SQLGrammarException (org.hibernate.exception.SQLGrammarException)8 HashMap (java.util.HashMap)6 Iterator (java.util.Iterator)6 Person (org.datanucleus.samples.annotations.models.company.Person)6 MessagesEvent (com.openmeap.event.MessagesEvent)5 SQLException (java.sql.SQLException)5