authoredArticles = new HashSet<>(); + + // constructors, getters and setters... + + Author() { + } + + public Author(String authorName) { + this.authorName = authorName; + } + + public String getAuthorId() { + return authorId; + } + + public void setAuthorId(String authorId) { + this.authorId = authorId; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public Editor getEditor() { + return editor; + } + + public void setEditor(Editor editor) { + this.editor = editor; + } + + public Set getAuthoredArticles() { + return authoredArticles; + } + + public void setAuthoredArticles(Set authoredArticles) { + this.authoredArticles = authoredArticles; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java new file mode 100644 index 0000000000..2c3f720e91 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Editor { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String editorId; + + private String editorName; + + @OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST) + private Set assignedAuthors = new HashSet<>(); + + // constructors, getters and setters... + + Editor() { + } + + public Editor(String editorName) { + this.editorName = editorName; + } + + public String getEditorId() { + return editorId; + } + + public void setEditorId(String editorId) { + this.editorId = editorId; + } + + public String getEditorName() { + return editorName; + } + + public void setEditorName(String editorName) { + this.editorName = editorName; + } + + public Set getAssignedAuthors() { + return assignedAuthors; + } + + public void setAssignedAuthors(Set assignedAuthors) { + this.assignedAuthors = assignedAuthors; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..43c86fb55b --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,24 @@ + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java new file mode 100644 index 0000000000..d7fd49d917 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.hibernate.ogm; + +import static org.fest.assertions.Assertions.assertThat; + +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.transaction.TransactionManager; + +import org.junit.Test; + +public class EditorUnitTest { + /* + @Test + public void givenMongoDB_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + */ + @Test + public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + + private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.persist(editor); + entityManager.close(); + transactionManager.commit(); + } + + private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId()); + assertThat(loadedEditor).isNotNull(); + assertThat(loadedEditor.getEditorName()).isEqualTo("Tom"); + assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName") + .containsOnly("Maria", "Mike"); + Map loadedAuthors = loadedEditor.getAssignedAuthors() + .stream() + .collect(Collectors.toMap(Author::getAuthorName, e -> e)); + assertThat(loadedAuthors.get("Maria") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Basic of Hibernate OGM"); + assertThat(loadedAuthors.get("Mike") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM"); + entityManager.close(); + transactionManager.commit(); + } + + private Editor generateTestData() { + Editor tom = new Editor("Tom"); + Author maria = new Author("Maria"); + Author mike = new Author("Mike"); + Article basic = new Article("Basic of Hibernate OGM"); + Article intermediate = new Article("Intermediate of Hibernate OGM"); + Article advanced = new Article("Advanced of Hibernate OGM"); + maria.getAuthoredArticles() + .add(basic); + basic.setAuthor(maria); + mike.getAuthoredArticles() + .add(intermediate); + intermediate.setAuthor(mike); + mike.getAuthoredArticles() + .add(advanced); + advanced.setAuthor(mike); + tom.getAssignedAuthors() + .add(maria); + maria.setEditor(tom); + tom.getAssignedAuthors() + .add(mike); + mike.setEditor(tom); + return tom; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index b6e112b5fc..03bdd9b759 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -21,3 +21,11 @@ - [Custom Types in Hibernate](https://www.baeldung.com/hibernate-custom-types) - [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) - [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) +- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) +- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) +- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) +- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index f5a3a7e4c9..af94025a73 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -1,11 +1,12 @@ - + 4.0.0 com.baeldung hibernate5 0.0.1-SNAPSHOT - hibernate5 + hibernate5 com.baeldung @@ -66,6 +67,12 @@ byte-buddy 1.9.5 + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + @@ -79,12 +86,12 @@ - 5.3.6.Final + 5.3.7.Final 6.0.6 2.2.3 1.4.196 3.8.0 - 2.8.11.3 + 2.9.7 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java new file mode 100644 index 0000000000..35cfe55ba6 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.criteriaquery; + +import com.baeldung.hibernate.customtypes.LocalDateStringType; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + private HibernateUtil() { + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(); + } + return sessionFactory; + } + + private static SessionFactory buildSessionFactory() { + try { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addAnnotatedClass(Student.class); + Metadata metadata = metadataSources.getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + return metadata.getSessionFactoryBuilder().build(); + } catch (IOException ex) { + throw new ExceptionInInitializerError(ex); + } + } + + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties).build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java new file mode 100644 index 0000000000..314e7ca557 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.criteriaquery; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "students") +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @Column(name = "grad_year") + private int gradYear; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getGradYear() { + return gradYear; + } + + public void setGradYear(int gradYear) { + this.gradYear = gradYear; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java new file mode 100644 index 0000000000..989fa1281a --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java @@ -0,0 +1,16 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Entity; + +@Entity +public class EntityWithNoId { + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java new file mode 100644 index 0000000000..ae5174ac9c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java @@ -0,0 +1,63 @@ +package com.baeldung.hibernate.exception; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) + throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); + } + return sessionFactory; + } + + private static SessionFactory makeSessionFactory( + ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Product.class); + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() + throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, + "hibernate-exception.properties")); + try (FileInputStream inputStream = new FileInputStream( + propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java new file mode 100644 index 0000000000..031fa38de0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Product { + + private int id; + + private String name; + private String description; + + @Id + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Column(nullable=false) + 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; + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java new file mode 100644 index 0000000000..19988b45be --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.pojo.Movie; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.BootstrapServiceRegistry; +import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +public class BootstrapAPIIntegrationTest { + + SessionFactory sessionFactory = null; + + @Test + public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException { + + BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder() + .build(); + + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry) + // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient. + //.configure() + .build(); + + MetadataSources metadataSources = new MetadataSources(standardRegistry); + metadataSources.addAnnotatedClass(Movie.class); + + Metadata metadata = metadataSources.getMetadataBuilder().build(); + + sessionFactory = metadata.buildSessionFactory(); + assertNotNull(sessionFactory); + sessionFactory.close(); + } + + @After + public void clean() throws IOException { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java new file mode 100644 index 0000000000..9d368fa27e --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate.criteriaquery; + +import com.baeldung.hibernate.criteriaquery.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.query.Query; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +public class TypeSafeCriteriaIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() { + + prepareData(); + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = cb.createQuery(Student.class); + + Root root = criteriaQuery.from(Student.class); + criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965)); + + Query query = session.createQuery(criteriaQuery); + List results = query.getResultList(); + + assertNotNull(results); + assertEquals(1, results.size()); + + Student student = results.get(0); + + assertEquals("Ken", student.getFirstName()); + assertEquals("Thompson", student.getLastName()); + assertEquals(1965, student.getGradYear()); + } + + private void prepareData() { + Student student1 = new Student(); + student1.setFirstName("Ken"); + student1.setLastName("Thompson"); + student1.setGradYear(1965); + + session.save(student1); + + Student student2 = new Student(); + student2.setFirstName("Dennis"); + student2.setLastName("Ritchie"); + student2.setGradYear(1963); + + session.save(student2); + session.getTransaction().commit(); + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java new file mode 100644 index 0000000000..3581c81daa --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java @@ -0,0 +1,425 @@ +package com.baeldung.hibernate.exception; + +import static org.hamcrest.CoreMatchers.isA; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import javax.persistence.OptimisticLockException; +import javax.persistence.PersistenceException; + +import org.hibernate.AnnotationException; +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.NonUniqueObjectException; +import org.hibernate.PropertyValueException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.StaleObjectStateException; +import org.hibernate.StaleStateException; +import org.hibernate.Transaction; +import org.hibernate.TransactionException; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Configuration; +import org.hibernate.exception.ConstraintViolationException; +import org.hibernate.exception.DataException; +import org.hibernate.exception.SQLGrammarException; +import org.hibernate.query.NativeQuery; +import org.hibernate.tool.schema.spi.CommandAcceptanceException; +import org.hibernate.tool.schema.spi.SchemaManagementException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateExceptionUnitTest { + + private static final Logger logger = LoggerFactory + .getLogger(HibernateExceptionUnitTest.class); + private SessionFactory sessionFactory; + + @Before + public void setUp() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private Configuration getConfiguration() { + Configuration cfg = new Configuration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.H2Dialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none"); + cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver"); + cfg.setProperty(AvailableSettings.URL, + "jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1"); + cfg.setProperty(AvailableSettings.USER, "sa"); + cfg.setProperty(AvailableSettings.PASS, ""); + return cfg; + } + + @Test + public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { + thrown.expectCause(isA(MappingException.class)); + thrown.expectMessage("Unknown entity: java.lang.String"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT", String.class); + query.getResultList(); + } + + @Test + @SuppressWarnings("rawtypes") + public void whenQueryExecuted_thenOK() { + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT"); + List results = query.getResultList(); + assertNotNull(results); + } + + @Test + public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { + thrown.expect(AnnotationException.class); + thrown.expectMessage("No identifier specified for entity"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(EntityWithNoId.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() { + thrown.expect(SchemaManagementException.class); + thrown.expectMessage("Schema-validation: missing table"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate"); + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void whenWrongDialectSpecified_thenCommandAcceptanceException() { + thrown.expect(SchemaManagementException.class); + thrown.expectCause(isA(CommandAcceptanceException.class)); + thrown.expectMessage("Halting on error : Error executing DDL"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.MySQLDialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update"); + + // This does not work due to hibernate bug + // cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true"); + cfg.getProperties() + .put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true); + + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(Product.class); + + SessionFactory sessionFactory = cfg.buildSessionFactory(); + Session session = null; + Transaction transaction = null; + try { + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product 1"); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + closeSessionFactoryQuietly(sessionFactory); + } + } + + @Test + public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from NON_EXISTING_TABLE", Product.class); + query.getResultList(); + } + + @Test + public void whenDuplicateIdSaved_thenConstraintViolationException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(ConstraintViolationException.class)); + thrown.expectMessage( + "ConstraintViolationException: could not execute statement"); + + Session session = null; + Transaction transaction = null; + + for (int i = 1; i <= 2; i++) { + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product " + i); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + } + + @Test + public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() { + thrown.expect(isA(PropertyValueException.class)); + thrown.expectMessage( + "not-null property references a null or transient value"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product = new Product(); + product.setId(1); + 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)); + thrown.expectMessage( + "org.hibernate.exception.DataException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from PRODUCT where id='wrongTypeId'", Product.class); + query.getResultList(); + } + + @Test + public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() { + thrown.expect(isA(NonUniqueObjectException.class)); + thrown.expectMessage( + "A different object with the same identifier value was already associated with the session"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(1); + product1.setName("Product 1"); + session.save(product1); + + Product product2 = new Product(); + product2.setId(1); + product2.setName("Product 2"); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenDeletingADeletedObject_thenOptimisticLockException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown.expectMessage( + "Batch update returned unexpected row count from update"); + thrown.expectCause(isA(StaleStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(12); + product1.setName("Product 12"); + session.save(product1); + transaction.commit(); + session.close(); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product2 = session.get(Product.class, 12); + session.createNativeQuery("delete from Product where id=12") + .executeUpdate(); + // We need to refresh to fix the error. + // session.refresh(product2); + session.delete(product2); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenUpdatingNonExistingObject_thenStaleStateException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown + .expectMessage("Row was updated or deleted by another transaction"); + thrown.expectCause(isA(StaleObjectStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.update(product1); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { + thrown.expect(isA(TransactionException.class)); + + Session session = null; + Transaction transaction = null; + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.save(product1); + transaction.setRollbackOnly(); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + private void rollbackTransactionQuietly(Transaction transaction) { + if (transaction != null && transaction.isActive()) { + try { + transaction.rollback(); + } catch (Exception e) { + logger.error("Exception while rolling back transaction", e); + } + } + } + + private void closeSessionQuietly(Session session) { + if (session != null) { + try { + session.close(); + } catch (Exception e) { + logger.error("Exception while closing session", e); + } + } + } + + private void closeSessionFactoryQuietly(SessionFactory sessionFactory) { + if (sessionFactory != null) { + try { + sessionFactory.close(); + } catch (Exception e) { + logger.error("Exception while closing sessionFactory", e); + } + } + } + + @Test + public void givenExistingEntity_whenIdUpdated_thenHibernateException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(HibernateException.class)); + thrown.expectMessage( + "identifier of an instance of com.baeldung.hibernate.exception.Product was altered"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(222); + product1.setName("Product 222"); + session.save(product1); + transaction.commit(); + closeSessionQuietly(session); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product2 = session.get(Product.class, 222); + product2.setId(333); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties new file mode 100644 index 0000000000..e08a23166d --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties @@ -0,0 +1,16 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:myexceptiondb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 + +hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index 2a92934a6e..2738ef85ff 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -5,7 +5,7 @@ com.baeldung java-cockroachdb 1.0-SNAPSHOT - java-cockroachdb + java-cockroachdb parent-modules @@ -22,15 +22,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 42.1.4 diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 3bab6faa29..7d843af9ea 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) diff --git a/persistence-modules/java-jdbi/pom.xml b/persistence-modules/java-jdbi/pom.xml index 9281f4fd9d..dfb31b26e8 100644 --- a/persistence-modules/java-jdbi/pom.xml +++ b/persistence-modules/java-jdbi/pom.xml @@ -27,15 +27,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 3.1.0 2.4.0 diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 9a90216519..2eea5e60b4 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,4 +2,5 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;â€](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;â€](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) diff --git a/persistence-modules/redis/README.md b/persistence-modules/redis/README.md index dd655ca7aa..21cd048693 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -1,5 +1,4 @@ ### Relevant Articles: - [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library) - [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson) -- [Intro to Lettuce – the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library) - +- [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 5795e9912b..50d28af3d1 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -144,8 +144,8 @@ public class JedisIntegrationTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - scores.keySet().forEach(player -> { - jedis.zadd(key, scores.get(player), player); + scores.entrySet().forEach(playerScore -> { + jedis.zadd(key, playerScore.getValue(), playerScore.getKey()); }); Set players = jedis.zrevrange(key, 0, 1); diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md new file mode 100644 index 0000000000..f093d4baf0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -0,0 +1,3 @@ +# Relevant Articles + +- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 0ea42b1cb7..d9d3a9f9b7 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -1,20 +1,18 @@ - - 4.0.0 - com.baeldung + + 4.0.0 spring-boot-persistence 0.1.0 - spring-boot-persistence - + spring-boot-persistence + parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 - + org.springframework.boot @@ -35,42 +33,30 @@ org.mockito mockito-core - ${mockito.version} test com.h2database h2 - ${h2database.version} runtime - + org.apache.tomcat tomcat-jdbc - ${tomcat-jdbc.version} mysql mysql-connector-java - ${mysql-connector-java.version} - - UTF-8 - 1.8 - 8.0.12 - 9.0.10 - 1.4.197 - 2.23.0 - - + spring-boot-persistence - - src/main/resources - true - + + src/main/resources + true + @@ -79,4 +65,14 @@ + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + 2.23.0 + + diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index ef90714347..547a905d91 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { @@ -41,7 +41,7 @@ public class H2JpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.boot.domain" }); + em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java similarity index 95% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java index f1c936e432..a2a676200a 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.domain; +package com.baeldung.boot.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java similarity index 63% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java index d897e17afe..bbc2865856 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java @@ -1,7 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.domain.GenericEntity; import org.springframework.data.jpa.repository.JpaRepository; +import com.baeldung.boot.domain.GenericEntity; + public interface GenericEntityRepository extends JpaRepository { } diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java new file mode 100644 index 0000000000..c5a5c291c6 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.springboothsqldb.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java new file mode 100644 index 0000000000..8229a1d1c0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java @@ -0,0 +1,33 @@ +package com.baeldung.springboothsqldb.application.controllers; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import com.baeldung.springboothsqldb.application.repositories.CustomerRepository; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerController { + + private final CustomerRepository customerRepository; + + @Autowired + public CustomerController(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + @PostMapping("/customers") + public Customer addCustomer(@RequestBody Customer customer) { + customerRepository.save(customer); + return customer; + } + + @GetMapping("/customers") + public List getCustomers() { + return (List) customerRepository.findAll(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java new file mode 100644 index 0000000000..636a80e272 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.springboothsqldb.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private String email; + + public Customer() {} + + public Customer(String name, String email) { + this.name = name; + this.email = email; + } + + public void setId(long id) { + this.id = id; + } + + public long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..a81aa62c43 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.springboothsqldb.application.repositories; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository {} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java new file mode 100644 index 0000000000..00fd378b05 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java @@ -0,0 +1,25 @@ +package com.baeldung.util; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.sql.Date; +import java.time.LocalDate; +import java.util.Optional; + +@Converter(autoApply = true) +public class LocalDateConverter implements AttributeConverter { + + @Override + public Date convertToDatabaseColumn(LocalDate localDate) { + return Optional.ofNullable(localDate) + .map(Date::valueOf) + .orElse(null); + } + + @Override + public LocalDate convertToEntityAttribute(Date date) { + return Optional.ofNullable(date) + .map(Date::toLocalDate) + .orElse(null); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties index 303ce33c25..b0caf4a809 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties @@ -1,16 +1,5 @@ -spring.datasource.tomcat.initial-size=15 -spring.datasource.tomcat.max-wait=20000 -spring.datasource.tomcat.max-active=50 -spring.datasource.tomcat.max-idle=15 -spring.datasource.tomcat.min-idle=8 -spring.datasource.tomcat.default-auto-commit=true -spring.datasource.url=jdbc:h2:mem:test -spring.datasource.username=root -spring.datasource.password= -spring.datasource.driver-class-name=org.h2.Driver - -spring.jpa.show-sql=false -spring.jpa.hibernate.ddl-auto=update -spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect -spring.jpa.properties.hibernate.id.new_generator_mappings=false +spring.datasource.driver-class-name = org.hsqldb.jdbc.JDBCDriver +spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1 +spring.datasource.username = sa +spring.datasource.password = +spring.jpa.hibernate.ddl-auto = create diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html index 2634e10380..344d4e59f5 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html +++ b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html @@ -40,4 +40,4 @@ - \ No newline at end of file +
getAuthoredArticles() { + return authoredArticles; + } + + public void setAuthoredArticles(Set authoredArticles) { + this.authoredArticles = authoredArticles; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java new file mode 100644 index 0000000000..2c3f720e91 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Editor { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String editorId; + + private String editorName; + + @OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST) + private Set assignedAuthors = new HashSet<>(); + + // constructors, getters and setters... + + Editor() { + } + + public Editor(String editorName) { + this.editorName = editorName; + } + + public String getEditorId() { + return editorId; + } + + public void setEditorId(String editorId) { + this.editorId = editorId; + } + + public String getEditorName() { + return editorName; + } + + public void setEditorName(String editorName) { + this.editorName = editorName; + } + + public Set getAssignedAuthors() { + return assignedAuthors; + } + + public void setAssignedAuthors(Set assignedAuthors) { + this.assignedAuthors = assignedAuthors; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..43c86fb55b --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,24 @@ + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java new file mode 100644 index 0000000000..d7fd49d917 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.hibernate.ogm; + +import static org.fest.assertions.Assertions.assertThat; + +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.transaction.TransactionManager; + +import org.junit.Test; + +public class EditorUnitTest { + /* + @Test + public void givenMongoDB_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + */ + @Test + public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + + private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.persist(editor); + entityManager.close(); + transactionManager.commit(); + } + + private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId()); + assertThat(loadedEditor).isNotNull(); + assertThat(loadedEditor.getEditorName()).isEqualTo("Tom"); + assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName") + .containsOnly("Maria", "Mike"); + Map loadedAuthors = loadedEditor.getAssignedAuthors() + .stream() + .collect(Collectors.toMap(Author::getAuthorName, e -> e)); + assertThat(loadedAuthors.get("Maria") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Basic of Hibernate OGM"); + assertThat(loadedAuthors.get("Mike") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM"); + entityManager.close(); + transactionManager.commit(); + } + + private Editor generateTestData() { + Editor tom = new Editor("Tom"); + Author maria = new Author("Maria"); + Author mike = new Author("Mike"); + Article basic = new Article("Basic of Hibernate OGM"); + Article intermediate = new Article("Intermediate of Hibernate OGM"); + Article advanced = new Article("Advanced of Hibernate OGM"); + maria.getAuthoredArticles() + .add(basic); + basic.setAuthor(maria); + mike.getAuthoredArticles() + .add(intermediate); + intermediate.setAuthor(mike); + mike.getAuthoredArticles() + .add(advanced); + advanced.setAuthor(mike); + tom.getAssignedAuthors() + .add(maria); + maria.setEditor(tom); + tom.getAssignedAuthors() + .add(mike); + mike.setEditor(tom); + return tom; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index b6e112b5fc..03bdd9b759 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -21,3 +21,11 @@ - [Custom Types in Hibernate](https://www.baeldung.com/hibernate-custom-types) - [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) - [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) +- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) +- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) +- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) +- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index f5a3a7e4c9..af94025a73 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -1,11 +1,12 @@ - + 4.0.0 com.baeldung hibernate5 0.0.1-SNAPSHOT - hibernate5 + hibernate5 com.baeldung @@ -66,6 +67,12 @@ byte-buddy 1.9.5 + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + @@ -79,12 +86,12 @@ - 5.3.6.Final + 5.3.7.Final 6.0.6 2.2.3 1.4.196 3.8.0 - 2.8.11.3 + 2.9.7 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java new file mode 100644 index 0000000000..35cfe55ba6 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.criteriaquery; + +import com.baeldung.hibernate.customtypes.LocalDateStringType; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + private HibernateUtil() { + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(); + } + return sessionFactory; + } + + private static SessionFactory buildSessionFactory() { + try { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addAnnotatedClass(Student.class); + Metadata metadata = metadataSources.getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + return metadata.getSessionFactoryBuilder().build(); + } catch (IOException ex) { + throw new ExceptionInInitializerError(ex); + } + } + + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties).build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java new file mode 100644 index 0000000000..314e7ca557 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.criteriaquery; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "students") +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @Column(name = "grad_year") + private int gradYear; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getGradYear() { + return gradYear; + } + + public void setGradYear(int gradYear) { + this.gradYear = gradYear; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java new file mode 100644 index 0000000000..989fa1281a --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java @@ -0,0 +1,16 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Entity; + +@Entity +public class EntityWithNoId { + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java new file mode 100644 index 0000000000..ae5174ac9c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java @@ -0,0 +1,63 @@ +package com.baeldung.hibernate.exception; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) + throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); + } + return sessionFactory; + } + + private static SessionFactory makeSessionFactory( + ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Product.class); + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() + throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, + "hibernate-exception.properties")); + try (FileInputStream inputStream = new FileInputStream( + propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java new file mode 100644 index 0000000000..031fa38de0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Product { + + private int id; + + private String name; + private String description; + + @Id + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Column(nullable=false) + 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; + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java new file mode 100644 index 0000000000..19988b45be --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.pojo.Movie; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.BootstrapServiceRegistry; +import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +public class BootstrapAPIIntegrationTest { + + SessionFactory sessionFactory = null; + + @Test + public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException { + + BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder() + .build(); + + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry) + // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient. + //.configure() + .build(); + + MetadataSources metadataSources = new MetadataSources(standardRegistry); + metadataSources.addAnnotatedClass(Movie.class); + + Metadata metadata = metadataSources.getMetadataBuilder().build(); + + sessionFactory = metadata.buildSessionFactory(); + assertNotNull(sessionFactory); + sessionFactory.close(); + } + + @After + public void clean() throws IOException { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java new file mode 100644 index 0000000000..9d368fa27e --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate.criteriaquery; + +import com.baeldung.hibernate.criteriaquery.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.query.Query; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +public class TypeSafeCriteriaIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() { + + prepareData(); + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = cb.createQuery(Student.class); + + Root root = criteriaQuery.from(Student.class); + criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965)); + + Query query = session.createQuery(criteriaQuery); + List results = query.getResultList(); + + assertNotNull(results); + assertEquals(1, results.size()); + + Student student = results.get(0); + + assertEquals("Ken", student.getFirstName()); + assertEquals("Thompson", student.getLastName()); + assertEquals(1965, student.getGradYear()); + } + + private void prepareData() { + Student student1 = new Student(); + student1.setFirstName("Ken"); + student1.setLastName("Thompson"); + student1.setGradYear(1965); + + session.save(student1); + + Student student2 = new Student(); + student2.setFirstName("Dennis"); + student2.setLastName("Ritchie"); + student2.setGradYear(1963); + + session.save(student2); + session.getTransaction().commit(); + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java new file mode 100644 index 0000000000..3581c81daa --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java @@ -0,0 +1,425 @@ +package com.baeldung.hibernate.exception; + +import static org.hamcrest.CoreMatchers.isA; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import javax.persistence.OptimisticLockException; +import javax.persistence.PersistenceException; + +import org.hibernate.AnnotationException; +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.NonUniqueObjectException; +import org.hibernate.PropertyValueException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.StaleObjectStateException; +import org.hibernate.StaleStateException; +import org.hibernate.Transaction; +import org.hibernate.TransactionException; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Configuration; +import org.hibernate.exception.ConstraintViolationException; +import org.hibernate.exception.DataException; +import org.hibernate.exception.SQLGrammarException; +import org.hibernate.query.NativeQuery; +import org.hibernate.tool.schema.spi.CommandAcceptanceException; +import org.hibernate.tool.schema.spi.SchemaManagementException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateExceptionUnitTest { + + private static final Logger logger = LoggerFactory + .getLogger(HibernateExceptionUnitTest.class); + private SessionFactory sessionFactory; + + @Before + public void setUp() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private Configuration getConfiguration() { + Configuration cfg = new Configuration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.H2Dialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none"); + cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver"); + cfg.setProperty(AvailableSettings.URL, + "jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1"); + cfg.setProperty(AvailableSettings.USER, "sa"); + cfg.setProperty(AvailableSettings.PASS, ""); + return cfg; + } + + @Test + public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { + thrown.expectCause(isA(MappingException.class)); + thrown.expectMessage("Unknown entity: java.lang.String"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT", String.class); + query.getResultList(); + } + + @Test + @SuppressWarnings("rawtypes") + public void whenQueryExecuted_thenOK() { + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT"); + List results = query.getResultList(); + assertNotNull(results); + } + + @Test + public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { + thrown.expect(AnnotationException.class); + thrown.expectMessage("No identifier specified for entity"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(EntityWithNoId.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() { + thrown.expect(SchemaManagementException.class); + thrown.expectMessage("Schema-validation: missing table"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate"); + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void whenWrongDialectSpecified_thenCommandAcceptanceException() { + thrown.expect(SchemaManagementException.class); + thrown.expectCause(isA(CommandAcceptanceException.class)); + thrown.expectMessage("Halting on error : Error executing DDL"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.MySQLDialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update"); + + // This does not work due to hibernate bug + // cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true"); + cfg.getProperties() + .put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true); + + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(Product.class); + + SessionFactory sessionFactory = cfg.buildSessionFactory(); + Session session = null; + Transaction transaction = null; + try { + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product 1"); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + closeSessionFactoryQuietly(sessionFactory); + } + } + + @Test + public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from NON_EXISTING_TABLE", Product.class); + query.getResultList(); + } + + @Test + public void whenDuplicateIdSaved_thenConstraintViolationException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(ConstraintViolationException.class)); + thrown.expectMessage( + "ConstraintViolationException: could not execute statement"); + + Session session = null; + Transaction transaction = null; + + for (int i = 1; i <= 2; i++) { + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product " + i); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + } + + @Test + public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() { + thrown.expect(isA(PropertyValueException.class)); + thrown.expectMessage( + "not-null property references a null or transient value"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product = new Product(); + product.setId(1); + 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)); + thrown.expectMessage( + "org.hibernate.exception.DataException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from PRODUCT where id='wrongTypeId'", Product.class); + query.getResultList(); + } + + @Test + public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() { + thrown.expect(isA(NonUniqueObjectException.class)); + thrown.expectMessage( + "A different object with the same identifier value was already associated with the session"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(1); + product1.setName("Product 1"); + session.save(product1); + + Product product2 = new Product(); + product2.setId(1); + product2.setName("Product 2"); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenDeletingADeletedObject_thenOptimisticLockException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown.expectMessage( + "Batch update returned unexpected row count from update"); + thrown.expectCause(isA(StaleStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(12); + product1.setName("Product 12"); + session.save(product1); + transaction.commit(); + session.close(); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product2 = session.get(Product.class, 12); + session.createNativeQuery("delete from Product where id=12") + .executeUpdate(); + // We need to refresh to fix the error. + // session.refresh(product2); + session.delete(product2); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenUpdatingNonExistingObject_thenStaleStateException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown + .expectMessage("Row was updated or deleted by another transaction"); + thrown.expectCause(isA(StaleObjectStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.update(product1); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { + thrown.expect(isA(TransactionException.class)); + + Session session = null; + Transaction transaction = null; + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.save(product1); + transaction.setRollbackOnly(); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + private void rollbackTransactionQuietly(Transaction transaction) { + if (transaction != null && transaction.isActive()) { + try { + transaction.rollback(); + } catch (Exception e) { + logger.error("Exception while rolling back transaction", e); + } + } + } + + private void closeSessionQuietly(Session session) { + if (session != null) { + try { + session.close(); + } catch (Exception e) { + logger.error("Exception while closing session", e); + } + } + } + + private void closeSessionFactoryQuietly(SessionFactory sessionFactory) { + if (sessionFactory != null) { + try { + sessionFactory.close(); + } catch (Exception e) { + logger.error("Exception while closing sessionFactory", e); + } + } + } + + @Test + public void givenExistingEntity_whenIdUpdated_thenHibernateException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(HibernateException.class)); + thrown.expectMessage( + "identifier of an instance of com.baeldung.hibernate.exception.Product was altered"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(222); + product1.setName("Product 222"); + session.save(product1); + transaction.commit(); + closeSessionQuietly(session); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product2 = session.get(Product.class, 222); + product2.setId(333); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties new file mode 100644 index 0000000000..e08a23166d --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties @@ -0,0 +1,16 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:myexceptiondb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 + +hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index 2a92934a6e..2738ef85ff 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -5,7 +5,7 @@ com.baeldung java-cockroachdb 1.0-SNAPSHOT - java-cockroachdb + java-cockroachdb parent-modules @@ -22,15 +22,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 42.1.4 diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 3bab6faa29..7d843af9ea 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) diff --git a/persistence-modules/java-jdbi/pom.xml b/persistence-modules/java-jdbi/pom.xml index 9281f4fd9d..dfb31b26e8 100644 --- a/persistence-modules/java-jdbi/pom.xml +++ b/persistence-modules/java-jdbi/pom.xml @@ -27,15 +27,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 3.1.0 2.4.0 diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 9a90216519..2eea5e60b4 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,4 +2,5 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;â€](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;â€](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) diff --git a/persistence-modules/redis/README.md b/persistence-modules/redis/README.md index dd655ca7aa..21cd048693 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -1,5 +1,4 @@ ### Relevant Articles: - [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library) - [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson) -- [Intro to Lettuce – the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library) - +- [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 5795e9912b..50d28af3d1 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -144,8 +144,8 @@ public class JedisIntegrationTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - scores.keySet().forEach(player -> { - jedis.zadd(key, scores.get(player), player); + scores.entrySet().forEach(playerScore -> { + jedis.zadd(key, playerScore.getValue(), playerScore.getKey()); }); Set players = jedis.zrevrange(key, 0, 1); diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md new file mode 100644 index 0000000000..f093d4baf0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -0,0 +1,3 @@ +# Relevant Articles + +- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 0ea42b1cb7..d9d3a9f9b7 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -1,20 +1,18 @@ - - 4.0.0 - com.baeldung + + 4.0.0 spring-boot-persistence 0.1.0 - spring-boot-persistence - + spring-boot-persistence + parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 - + org.springframework.boot @@ -35,42 +33,30 @@ org.mockito mockito-core - ${mockito.version} test com.h2database h2 - ${h2database.version} runtime - + org.apache.tomcat tomcat-jdbc - ${tomcat-jdbc.version} mysql mysql-connector-java - ${mysql-connector-java.version} - - UTF-8 - 1.8 - 8.0.12 - 9.0.10 - 1.4.197 - 2.23.0 - - + spring-boot-persistence - - src/main/resources - true - + + src/main/resources + true + @@ -79,4 +65,14 @@ + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + 2.23.0 + + diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index ef90714347..547a905d91 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { @@ -41,7 +41,7 @@ public class H2JpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.boot.domain" }); + em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java similarity index 95% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java index f1c936e432..a2a676200a 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.domain; +package com.baeldung.boot.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java similarity index 63% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java index d897e17afe..bbc2865856 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java @@ -1,7 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.domain.GenericEntity; import org.springframework.data.jpa.repository.JpaRepository; +import com.baeldung.boot.domain.GenericEntity; + public interface GenericEntityRepository extends JpaRepository { } diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java new file mode 100644 index 0000000000..c5a5c291c6 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.springboothsqldb.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java new file mode 100644 index 0000000000..8229a1d1c0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java @@ -0,0 +1,33 @@ +package com.baeldung.springboothsqldb.application.controllers; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import com.baeldung.springboothsqldb.application.repositories.CustomerRepository; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerController { + + private final CustomerRepository customerRepository; + + @Autowired + public CustomerController(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + @PostMapping("/customers") + public Customer addCustomer(@RequestBody Customer customer) { + customerRepository.save(customer); + return customer; + } + + @GetMapping("/customers") + public List getCustomers() { + return (List) customerRepository.findAll(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java new file mode 100644 index 0000000000..636a80e272 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.springboothsqldb.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private String email; + + public Customer() {} + + public Customer(String name, String email) { + this.name = name; + this.email = email; + } + + public void setId(long id) { + this.id = id; + } + + public long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..a81aa62c43 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.springboothsqldb.application.repositories; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository {} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java new file mode 100644 index 0000000000..00fd378b05 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java @@ -0,0 +1,25 @@ +package com.baeldung.util; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.sql.Date; +import java.time.LocalDate; +import java.util.Optional; + +@Converter(autoApply = true) +public class LocalDateConverter implements AttributeConverter { + + @Override + public Date convertToDatabaseColumn(LocalDate localDate) { + return Optional.ofNullable(localDate) + .map(Date::valueOf) + .orElse(null); + } + + @Override + public LocalDate convertToEntityAttribute(Date date) { + return Optional.ofNullable(date) + .map(Date::toLocalDate) + .orElse(null); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties index 303ce33c25..b0caf4a809 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties @@ -1,16 +1,5 @@ -spring.datasource.tomcat.initial-size=15 -spring.datasource.tomcat.max-wait=20000 -spring.datasource.tomcat.max-active=50 -spring.datasource.tomcat.max-idle=15 -spring.datasource.tomcat.min-idle=8 -spring.datasource.tomcat.default-auto-commit=true -spring.datasource.url=jdbc:h2:mem:test -spring.datasource.username=root -spring.datasource.password= -spring.datasource.driver-class-name=org.h2.Driver - -spring.jpa.show-sql=false -spring.jpa.hibernate.ddl-auto=update -spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect -spring.jpa.properties.hibernate.id.new_generator_mappings=false +spring.datasource.driver-class-name = org.hsqldb.jdbc.JDBCDriver +spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1 +spring.datasource.username = sa +spring.datasource.password = +spring.jpa.hibernate.ddl-auto = create diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html index 2634e10380..344d4e59f5 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html +++ b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html @@ -40,4 +40,4 @@ - \ No newline at end of file +
authoredArticles) { + this.authoredArticles = authoredArticles; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java new file mode 100644 index 0000000000..2c3f720e91 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Editor { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String editorId; + + private String editorName; + + @OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST) + private Set assignedAuthors = new HashSet<>(); + + // constructors, getters and setters... + + Editor() { + } + + public Editor(String editorName) { + this.editorName = editorName; + } + + public String getEditorId() { + return editorId; + } + + public void setEditorId(String editorId) { + this.editorId = editorId; + } + + public String getEditorName() { + return editorName; + } + + public void setEditorName(String editorName) { + this.editorName = editorName; + } + + public Set getAssignedAuthors() { + return assignedAuthors; + } + + public void setAssignedAuthors(Set assignedAuthors) { + this.assignedAuthors = assignedAuthors; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..43c86fb55b --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,24 @@ + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java new file mode 100644 index 0000000000..d7fd49d917 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.hibernate.ogm; + +import static org.fest.assertions.Assertions.assertThat; + +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.transaction.TransactionManager; + +import org.junit.Test; + +public class EditorUnitTest { + /* + @Test + public void givenMongoDB_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + */ + @Test + public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + + private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.persist(editor); + entityManager.close(); + transactionManager.commit(); + } + + private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId()); + assertThat(loadedEditor).isNotNull(); + assertThat(loadedEditor.getEditorName()).isEqualTo("Tom"); + assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName") + .containsOnly("Maria", "Mike"); + Map loadedAuthors = loadedEditor.getAssignedAuthors() + .stream() + .collect(Collectors.toMap(Author::getAuthorName, e -> e)); + assertThat(loadedAuthors.get("Maria") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Basic of Hibernate OGM"); + assertThat(loadedAuthors.get("Mike") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM"); + entityManager.close(); + transactionManager.commit(); + } + + private Editor generateTestData() { + Editor tom = new Editor("Tom"); + Author maria = new Author("Maria"); + Author mike = new Author("Mike"); + Article basic = new Article("Basic of Hibernate OGM"); + Article intermediate = new Article("Intermediate of Hibernate OGM"); + Article advanced = new Article("Advanced of Hibernate OGM"); + maria.getAuthoredArticles() + .add(basic); + basic.setAuthor(maria); + mike.getAuthoredArticles() + .add(intermediate); + intermediate.setAuthor(mike); + mike.getAuthoredArticles() + .add(advanced); + advanced.setAuthor(mike); + tom.getAssignedAuthors() + .add(maria); + maria.setEditor(tom); + tom.getAssignedAuthors() + .add(mike); + mike.setEditor(tom); + return tom; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index b6e112b5fc..03bdd9b759 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -21,3 +21,11 @@ - [Custom Types in Hibernate](https://www.baeldung.com/hibernate-custom-types) - [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) - [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) +- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) +- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) +- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) +- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index f5a3a7e4c9..af94025a73 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -1,11 +1,12 @@ - + 4.0.0 com.baeldung hibernate5 0.0.1-SNAPSHOT - hibernate5 + hibernate5 com.baeldung @@ -66,6 +67,12 @@ byte-buddy 1.9.5 + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + @@ -79,12 +86,12 @@ - 5.3.6.Final + 5.3.7.Final 6.0.6 2.2.3 1.4.196 3.8.0 - 2.8.11.3 + 2.9.7 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java new file mode 100644 index 0000000000..35cfe55ba6 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.criteriaquery; + +import com.baeldung.hibernate.customtypes.LocalDateStringType; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + private HibernateUtil() { + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(); + } + return sessionFactory; + } + + private static SessionFactory buildSessionFactory() { + try { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addAnnotatedClass(Student.class); + Metadata metadata = metadataSources.getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + return metadata.getSessionFactoryBuilder().build(); + } catch (IOException ex) { + throw new ExceptionInInitializerError(ex); + } + } + + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties).build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java new file mode 100644 index 0000000000..314e7ca557 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.criteriaquery; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "students") +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @Column(name = "grad_year") + private int gradYear; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getGradYear() { + return gradYear; + } + + public void setGradYear(int gradYear) { + this.gradYear = gradYear; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java new file mode 100644 index 0000000000..989fa1281a --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java @@ -0,0 +1,16 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Entity; + +@Entity +public class EntityWithNoId { + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java new file mode 100644 index 0000000000..ae5174ac9c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java @@ -0,0 +1,63 @@ +package com.baeldung.hibernate.exception; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) + throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); + } + return sessionFactory; + } + + private static SessionFactory makeSessionFactory( + ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Product.class); + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() + throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, + "hibernate-exception.properties")); + try (FileInputStream inputStream = new FileInputStream( + propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java new file mode 100644 index 0000000000..031fa38de0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Product { + + private int id; + + private String name; + private String description; + + @Id + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Column(nullable=false) + 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; + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java new file mode 100644 index 0000000000..19988b45be --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.pojo.Movie; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.BootstrapServiceRegistry; +import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +public class BootstrapAPIIntegrationTest { + + SessionFactory sessionFactory = null; + + @Test + public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException { + + BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder() + .build(); + + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry) + // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient. + //.configure() + .build(); + + MetadataSources metadataSources = new MetadataSources(standardRegistry); + metadataSources.addAnnotatedClass(Movie.class); + + Metadata metadata = metadataSources.getMetadataBuilder().build(); + + sessionFactory = metadata.buildSessionFactory(); + assertNotNull(sessionFactory); + sessionFactory.close(); + } + + @After + public void clean() throws IOException { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java new file mode 100644 index 0000000000..9d368fa27e --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate.criteriaquery; + +import com.baeldung.hibernate.criteriaquery.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.query.Query; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +public class TypeSafeCriteriaIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() { + + prepareData(); + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = cb.createQuery(Student.class); + + Root root = criteriaQuery.from(Student.class); + criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965)); + + Query query = session.createQuery(criteriaQuery); + List results = query.getResultList(); + + assertNotNull(results); + assertEquals(1, results.size()); + + Student student = results.get(0); + + assertEquals("Ken", student.getFirstName()); + assertEquals("Thompson", student.getLastName()); + assertEquals(1965, student.getGradYear()); + } + + private void prepareData() { + Student student1 = new Student(); + student1.setFirstName("Ken"); + student1.setLastName("Thompson"); + student1.setGradYear(1965); + + session.save(student1); + + Student student2 = new Student(); + student2.setFirstName("Dennis"); + student2.setLastName("Ritchie"); + student2.setGradYear(1963); + + session.save(student2); + session.getTransaction().commit(); + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java new file mode 100644 index 0000000000..3581c81daa --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java @@ -0,0 +1,425 @@ +package com.baeldung.hibernate.exception; + +import static org.hamcrest.CoreMatchers.isA; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import javax.persistence.OptimisticLockException; +import javax.persistence.PersistenceException; + +import org.hibernate.AnnotationException; +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.NonUniqueObjectException; +import org.hibernate.PropertyValueException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.StaleObjectStateException; +import org.hibernate.StaleStateException; +import org.hibernate.Transaction; +import org.hibernate.TransactionException; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Configuration; +import org.hibernate.exception.ConstraintViolationException; +import org.hibernate.exception.DataException; +import org.hibernate.exception.SQLGrammarException; +import org.hibernate.query.NativeQuery; +import org.hibernate.tool.schema.spi.CommandAcceptanceException; +import org.hibernate.tool.schema.spi.SchemaManagementException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateExceptionUnitTest { + + private static final Logger logger = LoggerFactory + .getLogger(HibernateExceptionUnitTest.class); + private SessionFactory sessionFactory; + + @Before + public void setUp() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private Configuration getConfiguration() { + Configuration cfg = new Configuration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.H2Dialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none"); + cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver"); + cfg.setProperty(AvailableSettings.URL, + "jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1"); + cfg.setProperty(AvailableSettings.USER, "sa"); + cfg.setProperty(AvailableSettings.PASS, ""); + return cfg; + } + + @Test + public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { + thrown.expectCause(isA(MappingException.class)); + thrown.expectMessage("Unknown entity: java.lang.String"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT", String.class); + query.getResultList(); + } + + @Test + @SuppressWarnings("rawtypes") + public void whenQueryExecuted_thenOK() { + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT"); + List results = query.getResultList(); + assertNotNull(results); + } + + @Test + public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { + thrown.expect(AnnotationException.class); + thrown.expectMessage("No identifier specified for entity"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(EntityWithNoId.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() { + thrown.expect(SchemaManagementException.class); + thrown.expectMessage("Schema-validation: missing table"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate"); + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void whenWrongDialectSpecified_thenCommandAcceptanceException() { + thrown.expect(SchemaManagementException.class); + thrown.expectCause(isA(CommandAcceptanceException.class)); + thrown.expectMessage("Halting on error : Error executing DDL"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.MySQLDialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update"); + + // This does not work due to hibernate bug + // cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true"); + cfg.getProperties() + .put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true); + + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(Product.class); + + SessionFactory sessionFactory = cfg.buildSessionFactory(); + Session session = null; + Transaction transaction = null; + try { + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product 1"); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + closeSessionFactoryQuietly(sessionFactory); + } + } + + @Test + public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from NON_EXISTING_TABLE", Product.class); + query.getResultList(); + } + + @Test + public void whenDuplicateIdSaved_thenConstraintViolationException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(ConstraintViolationException.class)); + thrown.expectMessage( + "ConstraintViolationException: could not execute statement"); + + Session session = null; + Transaction transaction = null; + + for (int i = 1; i <= 2; i++) { + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product " + i); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + } + + @Test + public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() { + thrown.expect(isA(PropertyValueException.class)); + thrown.expectMessage( + "not-null property references a null or transient value"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product = new Product(); + product.setId(1); + 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)); + thrown.expectMessage( + "org.hibernate.exception.DataException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from PRODUCT where id='wrongTypeId'", Product.class); + query.getResultList(); + } + + @Test + public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() { + thrown.expect(isA(NonUniqueObjectException.class)); + thrown.expectMessage( + "A different object with the same identifier value was already associated with the session"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(1); + product1.setName("Product 1"); + session.save(product1); + + Product product2 = new Product(); + product2.setId(1); + product2.setName("Product 2"); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenDeletingADeletedObject_thenOptimisticLockException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown.expectMessage( + "Batch update returned unexpected row count from update"); + thrown.expectCause(isA(StaleStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(12); + product1.setName("Product 12"); + session.save(product1); + transaction.commit(); + session.close(); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product2 = session.get(Product.class, 12); + session.createNativeQuery("delete from Product where id=12") + .executeUpdate(); + // We need to refresh to fix the error. + // session.refresh(product2); + session.delete(product2); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenUpdatingNonExistingObject_thenStaleStateException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown + .expectMessage("Row was updated or deleted by another transaction"); + thrown.expectCause(isA(StaleObjectStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.update(product1); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { + thrown.expect(isA(TransactionException.class)); + + Session session = null; + Transaction transaction = null; + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.save(product1); + transaction.setRollbackOnly(); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + private void rollbackTransactionQuietly(Transaction transaction) { + if (transaction != null && transaction.isActive()) { + try { + transaction.rollback(); + } catch (Exception e) { + logger.error("Exception while rolling back transaction", e); + } + } + } + + private void closeSessionQuietly(Session session) { + if (session != null) { + try { + session.close(); + } catch (Exception e) { + logger.error("Exception while closing session", e); + } + } + } + + private void closeSessionFactoryQuietly(SessionFactory sessionFactory) { + if (sessionFactory != null) { + try { + sessionFactory.close(); + } catch (Exception e) { + logger.error("Exception while closing sessionFactory", e); + } + } + } + + @Test + public void givenExistingEntity_whenIdUpdated_thenHibernateException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(HibernateException.class)); + thrown.expectMessage( + "identifier of an instance of com.baeldung.hibernate.exception.Product was altered"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(222); + product1.setName("Product 222"); + session.save(product1); + transaction.commit(); + closeSessionQuietly(session); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product2 = session.get(Product.class, 222); + product2.setId(333); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties new file mode 100644 index 0000000000..e08a23166d --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties @@ -0,0 +1,16 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:myexceptiondb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 + +hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index 2a92934a6e..2738ef85ff 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -5,7 +5,7 @@ com.baeldung java-cockroachdb 1.0-SNAPSHOT - java-cockroachdb + java-cockroachdb parent-modules @@ -22,15 +22,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 42.1.4 diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 3bab6faa29..7d843af9ea 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) diff --git a/persistence-modules/java-jdbi/pom.xml b/persistence-modules/java-jdbi/pom.xml index 9281f4fd9d..dfb31b26e8 100644 --- a/persistence-modules/java-jdbi/pom.xml +++ b/persistence-modules/java-jdbi/pom.xml @@ -27,15 +27,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 3.1.0 2.4.0 diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 9a90216519..2eea5e60b4 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,4 +2,5 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;â€](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;â€](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) diff --git a/persistence-modules/redis/README.md b/persistence-modules/redis/README.md index dd655ca7aa..21cd048693 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -1,5 +1,4 @@ ### Relevant Articles: - [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library) - [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson) -- [Intro to Lettuce – the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library) - +- [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 5795e9912b..50d28af3d1 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -144,8 +144,8 @@ public class JedisIntegrationTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - scores.keySet().forEach(player -> { - jedis.zadd(key, scores.get(player), player); + scores.entrySet().forEach(playerScore -> { + jedis.zadd(key, playerScore.getValue(), playerScore.getKey()); }); Set players = jedis.zrevrange(key, 0, 1); diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md new file mode 100644 index 0000000000..f093d4baf0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -0,0 +1,3 @@ +# Relevant Articles + +- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 0ea42b1cb7..d9d3a9f9b7 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -1,20 +1,18 @@ - - 4.0.0 - com.baeldung + + 4.0.0 spring-boot-persistence 0.1.0 - spring-boot-persistence - + spring-boot-persistence + parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 - + org.springframework.boot @@ -35,42 +33,30 @@ org.mockito mockito-core - ${mockito.version} test com.h2database h2 - ${h2database.version} runtime - + org.apache.tomcat tomcat-jdbc - ${tomcat-jdbc.version} mysql mysql-connector-java - ${mysql-connector-java.version} - - UTF-8 - 1.8 - 8.0.12 - 9.0.10 - 1.4.197 - 2.23.0 - - + spring-boot-persistence - - src/main/resources - true - + + src/main/resources + true + @@ -79,4 +65,14 @@ + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + 2.23.0 + + diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index ef90714347..547a905d91 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { @@ -41,7 +41,7 @@ public class H2JpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.boot.domain" }); + em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java similarity index 95% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java index f1c936e432..a2a676200a 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.domain; +package com.baeldung.boot.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java similarity index 63% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java index d897e17afe..bbc2865856 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java @@ -1,7 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.domain.GenericEntity; import org.springframework.data.jpa.repository.JpaRepository; +import com.baeldung.boot.domain.GenericEntity; + public interface GenericEntityRepository extends JpaRepository { } diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java new file mode 100644 index 0000000000..c5a5c291c6 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.springboothsqldb.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java new file mode 100644 index 0000000000..8229a1d1c0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java @@ -0,0 +1,33 @@ +package com.baeldung.springboothsqldb.application.controllers; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import com.baeldung.springboothsqldb.application.repositories.CustomerRepository; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerController { + + private final CustomerRepository customerRepository; + + @Autowired + public CustomerController(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + @PostMapping("/customers") + public Customer addCustomer(@RequestBody Customer customer) { + customerRepository.save(customer); + return customer; + } + + @GetMapping("/customers") + public List getCustomers() { + return (List) customerRepository.findAll(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java new file mode 100644 index 0000000000..636a80e272 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.springboothsqldb.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private String email; + + public Customer() {} + + public Customer(String name, String email) { + this.name = name; + this.email = email; + } + + public void setId(long id) { + this.id = id; + } + + public long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..a81aa62c43 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.springboothsqldb.application.repositories; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository {} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java new file mode 100644 index 0000000000..00fd378b05 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java @@ -0,0 +1,25 @@ +package com.baeldung.util; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.sql.Date; +import java.time.LocalDate; +import java.util.Optional; + +@Converter(autoApply = true) +public class LocalDateConverter implements AttributeConverter { + + @Override + public Date convertToDatabaseColumn(LocalDate localDate) { + return Optional.ofNullable(localDate) + .map(Date::valueOf) + .orElse(null); + } + + @Override + public LocalDate convertToEntityAttribute(Date date) { + return Optional.ofNullable(date) + .map(Date::toLocalDate) + .orElse(null); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties index 303ce33c25..b0caf4a809 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties @@ -1,16 +1,5 @@ -spring.datasource.tomcat.initial-size=15 -spring.datasource.tomcat.max-wait=20000 -spring.datasource.tomcat.max-active=50 -spring.datasource.tomcat.max-idle=15 -spring.datasource.tomcat.min-idle=8 -spring.datasource.tomcat.default-auto-commit=true -spring.datasource.url=jdbc:h2:mem:test -spring.datasource.username=root -spring.datasource.password= -spring.datasource.driver-class-name=org.h2.Driver - -spring.jpa.show-sql=false -spring.jpa.hibernate.ddl-auto=update -spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect -spring.jpa.properties.hibernate.id.new_generator_mappings=false +spring.datasource.driver-class-name = org.hsqldb.jdbc.JDBCDriver +spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1 +spring.datasource.username = sa +spring.datasource.password = +spring.jpa.hibernate.ddl-auto = create diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html index 2634e10380..344d4e59f5 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html +++ b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html @@ -40,4 +40,4 @@ - \ No newline at end of file +