@Provider public class PersistenceMapper implements ExceptionMapper<PersistenceException> { @Override public Response toResponse(PersistenceException arg0) { if(arg0.getCause() instanceof InvalidDataException) { return Response.status(Response.Status.BAD_REQUEST).build(); } else { ... } } }
/** * Trigger a flush on the given Hibernate Session, converting regular * {@link HibernateException} instances as well as Hibernate 5.2's * {@link PersistenceException} wrappers accordingly. * @param session the Hibernate Session to flush * @param synch whether this flush is triggered by transaction synchronization * @throws DataAccessException in case of flush failures * @since 4.3.2 */ static void flush(Session session, boolean synch) throws DataAccessException { if (synch) { logger.debug("Flushing Hibernate Session on transaction synchronization"); } else { logger.debug("Flushing Hibernate Session on explicit request"); } try { session.flush(); } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (PersistenceException ex) { if (ex.getCause() instanceof HibernateException) { throw convertHibernateAccessException((HibernateException) ex.getCause()); } throw ex; } }
@Override public void flush() { try { getSessionHolder().getSession().flush(); } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (PersistenceException ex) { if (ex.getCause() instanceof HibernateException) { throw convertHibernateAccessException((HibernateException) ex.getCause()); } throw ex; } } }
@Test(expected = ConstraintViolationException.class) public void updateSamWithNullDriversLicenseWithSessionFlush() throws Throwable { updateSamWithNullDriversLicense(); // Manual flush is required to avoid false positive in test try { sessionFactory.getCurrentSession().flush(); } catch (PersistenceException ex) { // Wrapped in Hibernate 5.2, with the constraint violation as cause throw ex.getCause(); } }
private EntityManagerFactory buildNativeEntityManagerFactory() { EntityManagerFactory emf; try { emf = createNativeEntityManagerFactory(); } catch (PersistenceException ex) { if (ex.getClass() == PersistenceException.class) { // Plain PersistenceException wrapper for underlying exception? // Make sure the nested exception message is properly exposed, // along the lines of Spring's NestedRuntimeException.getMessage() Throwable cause = ex.getCause(); if (cause != null) { String message = ex.getMessage(); String causeString = cause.toString(); if (!message.endsWith(causeString)) { throw new PersistenceException(message + "; nested exception is " + causeString, cause); } } } throw ex; } JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter(); if (jpaVendorAdapter != null) { jpaVendorAdapter.postProcessEntityManagerFactory(emf); } if (logger.isInfoEnabled()) { logger.info("Initialized JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'"); } return emf; }
@Override public void flush() { try { getSessionHolder().getSession().flush(); } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (PersistenceException ex) { if (ex.getCause() instanceof HibernateException) { throw convertHibernateAccessException((HibernateException) ex.getCause()); } throw ex; } } }
@Override protected void doCommit(DefaultTransactionStatus status) { HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction(); Transaction hibTx = txObject.getSessionHolder().getTransaction(); Assert.state(hibTx != null, "No Hibernate transaction"); if (status.isDebug()) { logger.debug("Committing Hibernate transaction on Session [" + txObject.getSessionHolder().getSession() + "]"); } try { hibTx.commit(); } catch (org.hibernate.TransactionException ex) { // assumably from commit call to the underlying JDBC connection throw new TransactionSystemException("Could not commit Hibernate transaction", ex); } catch (HibernateException ex) { // assumably failed to flush changes to database throw convertHibernateAccessException(ex); } catch (PersistenceException ex) { if (ex.getCause() instanceof HibernateException) { throw convertHibernateAccessException((HibernateException) ex.getCause()); } throw ex; } }
@Test public void test_sql_jpa_multi_entity_query_example() { try { doInJPA( this::entityManagerFactory, entityManager -> { //tag::sql-jpa-multi-entity-query-example[] List<Object> entities = entityManager.createNativeQuery( "SELECT * " + "FROM Person pr, Partner pt " + "WHERE pr.name = pt.name" ) .getResultList(); //end::sql-jpa-multi-entity-query-example[] assertEquals(2, entities.size()); }); fail("Should throw NonUniqueDiscoveredSqlAliasException!"); } catch (PersistenceException expected) { assertEquals( NonUniqueDiscoveredSqlAliasException.class, expected.getCause().getClass() ); } }
@Test public void testPessimisticLockWithUnionWhileExplicitlyDisablingFollowOnLockingThenFails() { final Session session = openSession(); session.beginTransaction(); sqlStatementInterceptor.getSqlQueries().clear(); try { List<Vehicle> vehicles = session.createQuery( "select v from Vehicle v" ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ).setFollowOnLocking( false ) ) .getResultList(); fail( "Should throw exception since Oracle does not support UNION if follow on locking is disabled" ); } catch ( PersistenceException expected ) { assertEquals( SQLGrammarException.class, expected.getCause().getClass() ); } }
private void checkException(Session mainSession, PersistenceException e) { final Throwable cause = e.getCause(); if ( cause instanceof JDBCException ) { // SQLServer will report this condition via a SQLException // when using its SNAPSHOT transaction isolation... if ( !(getDialect() instanceof SQLServerDialect && ((JDBCException) cause).getErrorCode() == 3960) ) { throw e; } else { // it seems to "lose track" of the transaction as well... mainSession.getTransaction().rollback(); mainSession.beginTransaction(); } } else if ( !(cause instanceof StaleObjectStateException) && !(cause instanceof StaleStateException) ) { fail( "expectd StaleObjectStateException or StaleStateException exception but is" + cause ); } }
@Test @TestForIssue( jiraKey = "HHH-11957") public void testSubstrWithStringUnits() { mostRecentStatementInspector.clear(); try { doInHibernate( this::sessionFactory, session -> { String value = session.createQuery( "select substr( e.description, 21, 11, octets ) from AnEntity e", String.class ).uniqueResult(); assertEquals( "description", value ); } ); fail( "Should have failed because substr cannot be used with string units." ); } catch (PersistenceException expected) { assertTrue( SQLGrammarException.class.isInstance( expected.getCause() ) ); } assertTrue( mostRecentStatementInspector.mostRecentSql.contains( "substr(" ) ); assertTrue( mostRecentStatementInspector.mostRecentSql.contains( "octets" ) ); }
@Test public void testPessimisticLockWithGroupByWhileExplicitlyDisablingFollowOnLockingThenFails() { final Session session = openSession(); session.beginTransaction(); sqlStatementInterceptor.getSqlQueries().clear(); try { List<Object[]> products = session.createQuery( "select count(p), p " + "from Product p " + "group by p.id, p.name " ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) .setFollowOnLocking( false ) ) .getResultList(); fail( "Should throw exception since Oracle does not support GROUP BY if follow on locking is disabled" ); } catch ( PersistenceException expected ) { assertEquals( SQLGrammarException.class, expected.getCause().getClass() ); } }
@Test public void testPessimisticLockWithDistinctWhileExplicitlyDisablingFollowOnLockingThenFails() { final Session session = openSession(); session.beginTransaction(); sqlStatementInterceptor.getSqlQueries().clear(); try { List<Product> products = session.createQuery( "select distinct p from Product p where p.id > 40", Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) .setFollowOnLocking( false ) ) .getResultList(); fail( "Should throw exception since Oracle does not support DISTINCT if follow on locking is disabled" ); } catch ( PersistenceException expected ) { assertEquals( SQLGrammarException.class, expected.getCause().getClass() ); } }
@Test public void testPessimisticLockWithMaxResultsAndOrderByWhileExplicitlyDisablingFollowOnLockingThenFails() { final Session session = openSession(); session.beginTransaction(); sqlStatementInterceptor.getSqlQueries().clear(); try { List<Product> products = session.createQuery( "select p from Product p order by p.id", Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) .setFollowOnLocking( false ) ) .setMaxResults( 10 ) .getResultList(); fail( "Should throw exception since Oracle does not support ORDER BY if follow on locking is disabled" ); } catch ( PersistenceException expected ) { assertEquals( SQLGrammarException.class, expected.getCause().getClass() ); } }
@Test public void testBidirForeignIdGenerator() { try { doInHibernate( this::sessionFactory, session -> { OwnerAddress address = new OwnerAddress(); address.setOwner( null ); session.persist( address ); session.flush(); fail( "should have failed with IdentifierGenerationException" ); } ); } catch (PersistenceException ex) { assertTyping( IdentifierGenerationException.class, ex.getCause() ); // expected } }
@Test public void testPessimisticLockWithFirstResultsWhileExplicitlyDisablingFollowOnLockingThenFails() { final Session session = openSession(); session.beginTransaction(); sqlStatementInterceptor.getSqlQueries().clear(); try { List<Product> products = session.createQuery( "select p from Product p", Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) .setFollowOnLocking( false ) ) .setFirstResult( 40 ) .setMaxResults( 10 ) .getResultList(); fail( "Should throw exception since Oracle does not support ORDER BY if follow on locking is disabled" ); } catch ( PersistenceException expected ) { assertEquals( SQLGrammarException.class, expected.getCause().getClass() ); } }
@Test public void test_sql_hibernate_multi_entity_query_example() { try { doInJPA( this::entityManagerFactory, entityManager -> { Session session = entityManager.unwrap( Session.class ); //tag::sql-hibernate-multi-entity-query-example[] List<Object> entities = session.createNativeQuery( "SELECT * " + "FROM Person pr, Partner pt " + "WHERE pr.name = pt.name" ) .list(); //end::sql-hibernate-multi-entity-query-example[] assertEquals( 2, entities.size() ); } ); fail( "Should throw NonUniqueDiscoveredSqlAliasException!" ); } catch (NonUniqueDiscoveredSqlAliasException e) { // expected } catch (PersistenceException e) { assertTyping( NonUniqueDiscoveredSqlAliasException.class, e.getCause() ); } }
@Test public void testUniqueConstraintWithEmptyColumnName() { doInHibernate( this::sessionFactory, session -> { Customer customer1 = new Customer(); customer1.customerId = "123"; session.persist( customer1 ); } ); try { doInHibernate( this::sessionFactory, session -> { Customer customer1 = new Customer(); customer1.customerId = "123"; session.persist( customer1 ); } ); fail( "Should throw" ); } catch ( PersistenceException e ) { assertEquals( ConstraintViolationException.class, e.getCause().getClass() ); } }