BAEL-6018: HibernateSystemException: ids for this class must be manually assigned before calling save() (#13121)

This commit is contained in:
Azhwani 2022-12-16 08:49:28 +01:00 committed by GitHub
parent ca6c1068e2
commit 7a2d457f58
3 changed files with 69 additions and 0 deletions

View File

@ -34,6 +34,7 @@ public class HibernateUtil {
ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Product.class);
metadataSources.addAnnotatedClass(ProductEntity.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()

View File

@ -0,0 +1,40 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "PRODUCT")
public class ProductEntity {
@Id
private Integer id;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -26,6 +26,7 @@ import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.hql.internal.ast.QuerySyntaxException;
import org.hibernate.id.IdentifierGenerationException;
import org.hibernate.query.NativeQuery;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
@ -222,6 +223,33 @@ public class HibernateExceptionUnitTest {
}
@Test
public void givenEntityWithoutId_whenCallingSave_thenThrowIdentifierGenerationException() {
thrown.expect(isA(IdentifierGenerationException.class));
thrown.expectMessage("ids for this class must be manually assigned before calling save(): com.baeldung.hibernate.exception.Product");
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
ProductEntity product = new ProductEntity();
product.setName("Product Name");
session.save(product);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
thrown.expectCause(isA(DataException.class));