Search in sources :

Example 6 with SQLGrammarException

use of org.hibernate.exception.SQLGrammarException in project hibernate-orm by hibernate.

the class CriteriaQueryTest method testProjectedCompositeId.

@Test
public void testProjectedCompositeId() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Course course = new Course();
    course.setCourseCode("HIB");
    course.setDescription("Hibernate Training");
    course.getCourseMeetings().add(new CourseMeeting(course, "Monday", 1, "1313 Mockingbird Lane"));
    s.save(course);
    s.flush();
    s.clear();
    List data = s.createCriteria(CourseMeeting.class).setProjection(Projections.id()).list();
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    try {
        s.createCriteria(CourseMeeting.class).setProjection(Projections.count("id")).list();
        fail("should have thrown SQLGrammarException");
    } catch (SQLGrammarException ex) {
    // expected
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    try {
        s.createCriteria(CourseMeeting.class).setProjection(Projections.countDistinct("id")).list();
        if (!getDialect().supportsTupleDistinctCounts()) {
            fail("expected SQLGrammarException");
        }
    } catch (SQLGrammarException ex) {
        if (!getDialect().supportsTupleDistinctCounts()) {
        // expected
        } else {
            throw ex;
        }
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    s.delete(course);
    t.commit();
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) SQLGrammarException(org.hibernate.exception.SQLGrammarException) List(java.util.List) ArrayList(java.util.ArrayList) Session(org.hibernate.Session) Test(org.junit.Test)

Example 7 with SQLGrammarException

use of org.hibernate.exception.SQLGrammarException in project hibernate-orm by hibernate.

the class CriteriaQueryTest method testDistinctProjectionsOfComponents.

@Test
public void testDistinctProjectionsOfComponents() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Course course = new Course();
    course.setCourseCode("HIB");
    course.setDescription("Hibernate Training");
    s.save(course);
    Student gavin = new Student();
    gavin.setName("Gavin King");
    gavin.setStudentNumber(667);
    gavin.setCityState(new CityState("Odessa", "WA"));
    s.save(gavin);
    Student xam = new Student();
    xam.setName("Max Rydahl Andersen");
    xam.setStudentNumber(101);
    xam.setPreferredCourse(course);
    xam.setCityState(new CityState("Odessa", "WA"));
    s.save(xam);
    Enrolment enrolment = new Enrolment();
    enrolment.setCourse(course);
    enrolment.setCourseCode(course.getCourseCode());
    enrolment.setSemester((short) 1);
    enrolment.setYear((short) 1999);
    enrolment.setStudent(xam);
    enrolment.setStudentNumber(xam.getStudentNumber());
    xam.getEnrolments().add(enrolment);
    s.save(enrolment);
    enrolment = new Enrolment();
    enrolment.setCourse(course);
    enrolment.setCourseCode(course.getCourseCode());
    enrolment.setSemester((short) 3);
    enrolment.setYear((short) 1998);
    enrolment.setStudent(gavin);
    enrolment.setStudentNumber(gavin.getStudentNumber());
    gavin.getEnrolments().add(enrolment);
    s.save(enrolment);
    s.flush();
    Object result = s.createCriteria(Student.class).setProjection(Projections.distinct(Property.forName("cityState"))).uniqueResult();
    assertTrue(result instanceof CityState);
    assertEquals(((CityState) result).getCity(), "Odessa");
    assertEquals(((CityState) result).getState(), "WA");
    result = s.createCriteria(Student.class).setProjection(Projections.distinct(Property.forName("cityState").as("cityState"))).addOrder(Order.asc("cityState")).uniqueResult();
    assertTrue(result instanceof CityState);
    assertEquals(((CityState) result).getCity(), "Odessa");
    assertEquals(((CityState) result).getState(), "WA");
    result = s.createCriteria(Student.class).setProjection(Projections.count("cityState.city")).uniqueResult();
    assertEquals(2, ((Long) result).longValue());
    result = s.createCriteria(Student.class).setProjection(Projections.countDistinct("cityState.city")).uniqueResult();
    assertEquals(1, ((Long) result).longValue());
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    try {
        result = s.createCriteria(Student.class).setProjection(Projections.count("cityState")).uniqueResult();
        if (!getDialect().supportsTupleCounts()) {
            fail("expected SQLGrammarException");
        }
        assertEquals(1, ((Long) result).longValue());
    } catch (SQLGrammarException ex) {
        if (!getDialect().supportsTupleCounts()) {
        // expected
        } else {
            throw ex;
        }
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    try {
        result = s.createCriteria(Student.class).setProjection(Projections.countDistinct("cityState")).uniqueResult();
        if (!getDialect().supportsTupleDistinctCounts()) {
            fail("expected SQLGrammarException");
        }
        assertEquals(1, ((Long) result).longValue());
    } catch (SQLGrammarException ex) {
        if (!getDialect().supportsTupleDistinctCounts()) {
        // expected
        } else {
            throw ex;
        }
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    s.delete(gavin);
    s.delete(xam);
    s.delete(course);
    t.commit();
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) SQLGrammarException(org.hibernate.exception.SQLGrammarException) Session(org.hibernate.Session) Test(org.junit.Test)

Example 8 with SQLGrammarException

use of org.hibernate.exception.SQLGrammarException in project hibernate-orm by hibernate.

the class SQLExceptionConversionTest method testBadGrammar.

@Test
public void testBadGrammar() throws Exception {
    final Session session = openSession();
    session.beginTransaction();
    session.doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            // prepare/execute a query against a non-existent table
            PreparedStatement ps = null;
            try {
                ps = ((SessionImplementor) session).getJdbcCoordinator().getStatementPreparer().prepareStatement("SELECT user_id, user_name FROM tbl_no_there");
                ((SessionImplementor) session).getJdbcCoordinator().getResultSetReturn().extract(ps);
                fail("SQL compilation should have failed");
            } catch (SQLGrammarException ignored) {
            // expected outcome
            } finally {
                releaseStatement(session, ps);
            }
        }
    });
    session.getTransaction().rollback();
    session.close();
}
Also used : SQLGrammarException(org.hibernate.exception.SQLGrammarException) SQLException(java.sql.SQLException) Work(org.hibernate.jdbc.Work) Connection(java.sql.Connection) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) PreparedStatement(java.sql.PreparedStatement) Session(org.hibernate.Session) Test(org.junit.Test)

Example 9 with SQLGrammarException

use of org.hibernate.exception.SQLGrammarException in project hibernate-orm by hibernate.

the class RepeatableReadTest method testStaleVersionedInstanceFoundOnLock.

@Test
public void testStaleVersionedInstanceFoundOnLock() {
    if (!readCommittedIsolationMaintained("repeatable read tests")) {
        return;
    }
    String check = "EJB3 Specification";
    Session s1 = sessionFactory().openSession();
    Transaction t1 = s1.beginTransaction();
    Item item = new Item(check);
    s1.save(item);
    t1.commit();
    s1.close();
    Long itemId = item.getId();
    long initialVersion = item.getVersion();
    // Now, open a new Session and re-load the item...
    s1 = sessionFactory().openSession();
    t1 = s1.beginTransaction();
    item = (Item) s1.get(Item.class, itemId);
    // now that the item is associated with the persistence-context of that session,
    // open a new session and modify it "behind the back" of the first session
    Session s2 = sessionFactory().openSession();
    Transaction t2 = s2.beginTransaction();
    Item item2 = (Item) s2.get(Item.class, itemId);
    item2.setName("EJB3 Persistence Spec");
    t2.commit();
    s2.close();
    // at this point, s1 now contains stale data, so acquire a READ lock
    // and make sure we get the already associated state (i.e., the old
    // name and the old version)
    s1.lock(item, LockMode.READ);
    item2 = (Item) s1.get(Item.class, itemId);
    assertTrue(item == item2);
    assertEquals("encountered non-repeatable read", check, item2.getName());
    assertEquals("encountered non-repeatable read", initialVersion, item2.getVersion());
    // attempt to acquire an UPGRADE lock; this should fail
    try {
        s1.lock(item, LockMode.UPGRADE);
        fail("expected UPGRADE lock failure");
    } catch (StaleObjectStateException expected) {
    // this is the expected behavior
    } catch (SQLGrammarException t) {
        if (getDialect() instanceof SQLServerDialect) {
            // sql-server (using snapshot isolation) reports this as a grammar exception /:)
            //
            // not to mention that it seems to "lose track" of the transaction in this scenario...
            t1.rollback();
            t1 = s1.beginTransaction();
        } else {
            throw t;
        }
    }
    t1.commit();
    s1.close();
    // clean up
    s1 = sessionFactory().openSession();
    t1 = s1.beginTransaction();
    s1.createQuery("delete Item").executeUpdate();
    t1.commit();
    s1.close();
}
Also used : Item(org.hibernate.test.jpa.Item) SQLServerDialect(org.hibernate.dialect.SQLServerDialect) Transaction(org.hibernate.Transaction) SQLGrammarException(org.hibernate.exception.SQLGrammarException) StaleObjectStateException(org.hibernate.StaleObjectStateException) Session(org.hibernate.Session) Test(org.junit.Test) AbstractJPATest(org.hibernate.test.jpa.AbstractJPATest)

Example 10 with SQLGrammarException

use of org.hibernate.exception.SQLGrammarException in project uPortal by Jasig.

the class JpaVersionDao method getSimpleVersion.

/**
     * Load a Version object with direct field queries. Used to deal with DB upgrades where not all
     * of the fields have been loaded
     */
private Version getSimpleVersion(String product) {
    final Tuple coreNumbers;
    try {
        final TypedQuery<Tuple> coreNumbersQuery = this.createQuery(this.findCoreVersionNumbers);
        coreNumbersQuery.setParameter(this.productParameter, product);
        coreNumbers = DataAccessUtils.singleResult(coreNumbersQuery.getResultList());
    } catch (SQLGrammarException e) {
        logger.warn("UP_VERSION table doesn't exist, returning null for version of " + product);
        return null;
    }
    if (coreNumbers == null) {
        //Table exists but no version data for the product
        return null;
    }
    //Pull out the maj/min/pat values
    final Integer major = coreNumbers.get(VersionImpl_.major.getName(), VersionImpl_.major.getBindableJavaType());
    final Integer minor = coreNumbers.get(VersionImpl_.minor.getName(), VersionImpl_.minor.getBindableJavaType());
    final Integer patch = coreNumbers.get(VersionImpl_.patch.getName(), VersionImpl_.patch.getBindableJavaType());
    //See if the optional local version value exists
    Integer local;
    try {
        final TypedQuery<Integer> localNumberQuery = this.createQuery(this.findLocalVersionNumber);
        localNumberQuery.setParameter(this.productParameter, product);
        local = DataAccessUtils.singleResult(localNumberQuery.getResultList());
    } catch (PersistenceException e) {
        local = null;
    }
    return new VersionImpl(product, major, minor, patch, local);
}
Also used : SQLGrammarException(org.hibernate.exception.SQLGrammarException) PersistenceException(javax.persistence.PersistenceException) Tuple(javax.persistence.Tuple)

Aggregations

SQLGrammarException (org.hibernate.exception.SQLGrammarException)10 Test (org.junit.Test)8 Session (org.hibernate.Session)7 Transaction (org.hibernate.Transaction)5 PersistenceException (javax.persistence.PersistenceException)3 List (java.util.List)2 SkipForDialect (org.hibernate.testing.SkipForDialect)2 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 EntityManager (javax.persistence.EntityManager)1 Tuple (javax.persistence.Tuple)1 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)1 PessimisticLockException (org.hibernate.PessimisticLockException)1 QueryTimeoutException (org.hibernate.QueryTimeoutException)1 StaleObjectStateException (org.hibernate.StaleObjectStateException)1 SQLServerDialect (org.hibernate.dialect.SQLServerDialect)1 HQLQueryPlan (org.hibernate.engine.query.spi.HQLQueryPlan)1 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)1