BAEL-5697: Add new section in Hibernate Exceptions article (#12797)

This commit is contained in:
Azhwani 2022-10-09 21:18:50 +02:00 committed by GitHub
parent c18ce8a0cf
commit c68ee78e45
2 changed files with 33 additions and 37 deletions

View File

@ -3,12 +3,14 @@ package com.baeldung.hibernate.exception;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table;
@Entity @Entity
@Table(name = "PRODUCT")
public class Product { public class Product {
private int id; private int id;
private String name; private String name;
private String description; private String description;
@ -20,8 +22,8 @@ public class Product {
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
@Column(nullable=false) @Column(nullable = false)
public String getName() { public String getName() {
return name; return name;
} }

View File

@ -25,6 +25,7 @@ import org.hibernate.cfg.Configuration;
import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException; import org.hibernate.exception.DataException;
import org.hibernate.exception.SQLGrammarException; import org.hibernate.exception.SQLGrammarException;
import org.hibernate.hql.internal.ast.QuerySyntaxException;
import org.hibernate.query.NativeQuery; import org.hibernate.query.NativeQuery;
import org.hibernate.tool.schema.spi.CommandAcceptanceException; import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException; import org.hibernate.tool.schema.spi.SchemaManagementException;
@ -37,8 +38,7 @@ import org.slf4j.LoggerFactory;
public class HibernateExceptionUnitTest { public class HibernateExceptionUnitTest {
private static final Logger logger = LoggerFactory private static final Logger logger = LoggerFactory.getLogger(HibernateExceptionUnitTest.class);
.getLogger(HibernateExceptionUnitTest.class);
private SessionFactory sessionFactory; private SessionFactory sessionFactory;
@Before @Before
@ -51,12 +51,10 @@ public class HibernateExceptionUnitTest {
private Configuration getConfiguration() { private Configuration getConfiguration() {
Configuration cfg = new Configuration(); Configuration cfg = new Configuration();
cfg.setProperty(AvailableSettings.DIALECT, cfg.setProperty(AvailableSettings.DIALECT, "org.hibernate.dialect.H2Dialect");
"org.hibernate.dialect.H2Dialect");
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none"); cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none");
cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver"); cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver");
cfg.setProperty(AvailableSettings.URL, cfg.setProperty(AvailableSettings.URL, "jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1");
"jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1");
cfg.setProperty(AvailableSettings.USER, "sa"); cfg.setProperty(AvailableSettings.USER, "sa");
cfg.setProperty(AvailableSettings.PASS, ""); cfg.setProperty(AvailableSettings.PASS, "");
return cfg; return cfg;
@ -68,8 +66,7 @@ public class HibernateExceptionUnitTest {
thrown.expectMessage("Unknown entity: java.lang.String"); thrown.expectMessage("Unknown entity: java.lang.String");
Session session = sessionFactory.openSession(); Session session = sessionFactory.openSession();
NativeQuery<String> query = session NativeQuery<String> query = session.createNativeQuery("select name from PRODUCT", String.class);
.createNativeQuery("select name from PRODUCT", String.class);
query.getResultList(); query.getResultList();
} }
@ -77,12 +74,21 @@ public class HibernateExceptionUnitTest {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void whenQueryExecuted_thenOK() { public void whenQueryExecuted_thenOK() {
Session session = sessionFactory.openSession(); Session session = sessionFactory.openSession();
NativeQuery query = session NativeQuery query = session.createNativeQuery("select name from PRODUCT");
.createNativeQuery("select name from PRODUCT");
List results = query.getResultList(); List results = query.getResultList();
assertNotNull(results); assertNotNull(results);
} }
@Test
public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() {
thrown.expectCause(isA(QuerySyntaxException.class));
thrown.expectMessage("PRODUCT is not mapped [from PRODUCT]");
Session session = sessionFactory.openSession();
List<Product> results = session.createQuery("from PRODUCT", Product.class)
.getResultList();
}
@Test @Test
public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() {
thrown.expect(AnnotationException.class); thrown.expect(AnnotationException.class);
@ -111,8 +117,7 @@ public class HibernateExceptionUnitTest {
thrown.expectMessage("Halting on error : Error executing DDL"); thrown.expectMessage("Halting on error : Error executing DDL");
Configuration cfg = getConfiguration(); Configuration cfg = getConfiguration();
cfg.setProperty(AvailableSettings.DIALECT, cfg.setProperty(AvailableSettings.DIALECT, "org.hibernate.dialect.MySQLDialect");
"org.hibernate.dialect.MySQLDialect");
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update"); cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update");
// This does not work due to hibernate bug // This does not work due to hibernate bug
@ -128,8 +133,7 @@ public class HibernateExceptionUnitTest {
public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class)); thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class)); thrown.expectCause(isA(SQLGrammarException.class));
thrown thrown.expectMessage("SQLGrammarException: could not prepare statement");
.expectMessage("SQLGrammarException: could not prepare statement");
Configuration cfg = getConfiguration(); Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(Product.class); cfg.addAnnotatedClass(Product.class);
@ -159,12 +163,10 @@ public class HibernateExceptionUnitTest {
public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class)); thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class)); thrown.expectCause(isA(SQLGrammarException.class));
thrown thrown.expectMessage("SQLGrammarException: could not prepare statement");
.expectMessage("SQLGrammarException: could not prepare statement");
Session session = sessionFactory.openSession(); Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery( NativeQuery<Product> query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class);
"select * from NON_EXISTING_TABLE", Product.class);
query.getResultList(); query.getResultList();
} }
@ -172,8 +174,7 @@ public class HibernateExceptionUnitTest {
public void whenDuplicateIdSaved_thenConstraintViolationException() { public void whenDuplicateIdSaved_thenConstraintViolationException() {
thrown.expect(isA(PersistenceException.class)); thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(ConstraintViolationException.class)); thrown.expectCause(isA(ConstraintViolationException.class));
thrown.expectMessage( thrown.expectMessage("ConstraintViolationException: could not execute statement");
"ConstraintViolationException: could not execute statement");
Session session = null; Session session = null;
Transaction transaction = null; Transaction transaction = null;
@ -199,8 +200,7 @@ public class HibernateExceptionUnitTest {
@Test @Test
public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() { public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() {
thrown.expect(isA(PropertyValueException.class)); thrown.expect(isA(PropertyValueException.class));
thrown.expectMessage( thrown.expectMessage("not-null property references a null or transient value");
"not-null property references a null or transient value");
Session session = null; Session session = null;
Transaction transaction = null; Transaction transaction = null;
@ -225,20 +225,17 @@ public class HibernateExceptionUnitTest {
@Test @Test
public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() { public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
thrown.expectCause(isA(DataException.class)); thrown.expectCause(isA(DataException.class));
thrown.expectMessage( thrown.expectMessage("org.hibernate.exception.DataException: could not prepare statement");
"org.hibernate.exception.DataException: could not prepare statement");
Session session = sessionFactory.openSession(); Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery( NativeQuery<Product> query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class);
"select * from PRODUCT where id='wrongTypeId'", Product.class);
query.getResultList(); query.getResultList();
} }
@Test @Test
public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() { public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() {
thrown.expect(isA(NonUniqueObjectException.class)); thrown.expect(isA(NonUniqueObjectException.class));
thrown.expectMessage( thrown.expectMessage("A different object with the same identifier value was already associated with the session");
"A different object with the same identifier value was already associated with the session");
Session session = null; Session session = null;
Transaction transaction = null; Transaction transaction = null;
@ -269,8 +266,7 @@ public class HibernateExceptionUnitTest {
@Test @Test
public void whenDeletingADeletedObject_thenOptimisticLockException() { public void whenDeletingADeletedObject_thenOptimisticLockException() {
thrown.expect(isA(OptimisticLockException.class)); thrown.expect(isA(OptimisticLockException.class));
thrown.expectMessage( thrown.expectMessage("Batch update returned unexpected row count from update");
"Batch update returned unexpected row count from update");
thrown.expectCause(isA(StaleStateException.class)); thrown.expectCause(isA(StaleStateException.class));
Session session = null; Session session = null;
@ -307,8 +303,7 @@ public class HibernateExceptionUnitTest {
@Test @Test
public void whenUpdatingNonExistingObject_thenStaleStateException() { public void whenUpdatingNonExistingObject_thenStaleStateException() {
thrown.expect(isA(OptimisticLockException.class)); thrown.expect(isA(OptimisticLockException.class));
thrown thrown.expectMessage("Row was updated or deleted by another transaction");
.expectMessage("Row was updated or deleted by another transaction");
thrown.expectCause(isA(StaleObjectStateException.class)); thrown.expectCause(isA(StaleObjectStateException.class));
Session session = null; Session session = null;
@ -390,8 +385,7 @@ public class HibernateExceptionUnitTest {
public void givenExistingEntity_whenIdUpdated_thenHibernateException() { public void givenExistingEntity_whenIdUpdated_thenHibernateException() {
thrown.expect(isA(PersistenceException.class)); thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(HibernateException.class)); thrown.expectCause(isA(HibernateException.class));
thrown.expectMessage( thrown.expectMessage("identifier of an instance of com.baeldung.hibernate.exception.Product was altered");
"identifier of an instance of com.baeldung.hibernate.exception.Product was altered");
Session session = null; Session session = null;
Transaction transaction = null; Transaction transaction = null;