From 7cbc45c95aa939462b93db5cc2e987c2259600fe Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:15:02 +0530 Subject: [PATCH 01/17] JAVA-4 : Module pom update --- persistence-modules/pom.xml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 15b62d5d77..2e9b033b79 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,9 +21,13 @@ flyway hbase hibernate5 - hibernate5-2 hibernate-mapping hibernate-ogm + hibernate5-mapping + hibernate5-annotations + hibernate5-jpa + hibernate5-queries + hibernate5-enterprise influxdb java-cassandra java-cockroachdb From 25d015b3dfb6f62a1c6493c66225a3dc9e14c3fb Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:17:43 +0530 Subject: [PATCH 02/17] JAVA-4 : Removed hibernate5-2 module, moved its artifacts to other modules - hibernate-jpa and hibernate-enterprise --- persistence-modules/hibernate5-2/README.md | 11 --- persistence-modules/hibernate5-2/pom.xml | 74 --------------- .../baeldung/hibernate/logging/Employee.java | 59 ------------ .../baeldung/hibernateparameters/Event.java | 30 ------- .../PersistenceContextDemoApplication.java | 13 --- .../persistencecontext/entity/User.java | 36 -------- ...ExtendedPersistenceContextUserService.java | 33 ------- ...ansctionPersistenceContextUserService.java | 32 ------- .../hibernateparameters/Event.hbm.xml | 15 ---- .../main/resources/hibernate-logging.cfg.xml | 27 ------ .../src/main/resources/hibernate.cfg.xml | 28 ------ .../HibernateLoggingIntegrationTest.java | 50 ----------- .../NamedParameterUnitTest.java | 73 --------------- .../PersistenceContextIntegrationTest.java | 90 ------------------- .../hibernate5-2/src/test/resources/log4j.xml | 25 ------ .../src/test/resources/log4j2.xml | 18 ---- .../src/test/resources/logback.xml | 18 ---- 17 files changed, 632 deletions(-) delete mode 100644 persistence-modules/hibernate5-2/README.md delete mode 100644 persistence-modules/hibernate5-2/pom.xml delete mode 100644 persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java delete mode 100644 persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java delete mode 100644 persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java delete mode 100644 persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java delete mode 100644 persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java delete mode 100644 persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java delete mode 100644 persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml delete mode 100644 persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml delete mode 100644 persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml delete mode 100644 persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java delete mode 100644 persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java delete mode 100644 persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java delete mode 100644 persistence-modules/hibernate5-2/src/test/resources/log4j.xml delete mode 100644 persistence-modules/hibernate5-2/src/test/resources/log4j2.xml delete mode 100644 persistence-modules/hibernate5-2/src/test/resources/logback.xml diff --git a/persistence-modules/hibernate5-2/README.md b/persistence-modules/hibernate5-2/README.md deleted file mode 100644 index 330708f6d3..0000000000 --- a/persistence-modules/hibernate5-2/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Hibernate 5 - -This module contains articles about Hibernate 5. - -### Relevant Articles: -- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) -- [FetchMode in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-fetchmode) -- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) -- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) -- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) -- [[<-- Prev]](/hibernate5) diff --git a/persistence-modules/hibernate5-2/pom.xml b/persistence-modules/hibernate5-2/pom.xml deleted file mode 100644 index 15d42b3244..0000000000 --- a/persistence-modules/hibernate5-2/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - hibernate5-2 - 0.1-SNAPSHOT - hibernate5-2 - jar - Hibernate tutorial illustrating the use of named parameters - - - com.baeldung - persistence-modules - 1.0.0-SNAPSHOT - - - - - org.hibernate - hibernate-core - ${hibernate-core.version} - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-thymeleaf - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring-boot.version} - - - com.zaxxer - HikariCP - - - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - - - - com.h2database - h2 - ${h2.version} - - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - - - 5.4.7.Final - 1.4.200 - 3.8.1 - true - 2.1.7.RELEASE - 5.4.7.Final - 1.4.200 - 3.8.1 - - - diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java deleted file mode 100644 index 9dcf4058a7..0000000000 --- a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.hibernate.logging; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Employee { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private long id; - - private String employeeNumber; - - private String title; - - private String name; - - public Employee() { - } - - public Employee(String name, String employeeNumber) { - this.name = name; - this.employeeNumber = employeeNumber; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getEmployeeNumber() { - return employeeNumber; - } - - public void setEmployeeNumber(String employeeNumber) { - this.employeeNumber = employeeNumber; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } -} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java deleted file mode 100644 index 7912659a09..0000000000 --- a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.hibernateparameters; - -public class Event { - private Long id; - - private String title; - - public Event() { - } - - public Event(String title) { - this.title = title; - } - - public Long getId() { - return id; - } - - private void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java deleted file mode 100644 index 17fa582e10..0000000000 --- a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.persistencecontext; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan(basePackages="com.baeldung.persistencecontext") -public class PersistenceContextDemoApplication { - public static void main(String[] args) { - SpringApplication.run(PersistenceContextDemoApplication.class, args); - } -} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java deleted file mode 100644 index 7252ac46f5..0000000000 --- a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.persistencecontext.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class User { - - @Id - private Long id; - private String name; - private String role; - - public User() { - - } - - public User(Long id, String name, String role) { - this.id = id; - this.name = name; - this.role = role; - } - - public Long getId() { - return id; - } - - public String getName() { - return name; - } - - public String getRole() { - return role; - } - -} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java deleted file mode 100644 index ef25aac69f..0000000000 --- a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.persistencecontext.service; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.transaction.Transactional; - -import org.springframework.stereotype.Component; - -import com.baeldung.persistencecontext.entity.User; - -@Component -public class ExtendedPersistenceContextUserService { - - @PersistenceContext(type = PersistenceContextType.EXTENDED) - private EntityManager entityManager; - - @Transactional - public User insertWithTransaction(User user) { - entityManager.persist(user); - return user; - } - - public User insertWithoutTransaction(User user) { - entityManager.persist(user); - return user; - } - - public User find(long id) { - User user = entityManager.find(User.class, id); - return user; - } -} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java deleted file mode 100644 index 481defcf08..0000000000 --- a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.persistencecontext.service; - - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.transaction.Transactional; - -import org.springframework.stereotype.Component; - -import com.baeldung.persistencecontext.entity.User; - -@Component -public class TransctionPersistenceContextUserService { - - @PersistenceContext - private EntityManager entityManager; - - @Transactional - public User insertWithTransaction(User user) { - entityManager.persist(user); - return user; - } - - public User insertWithoutTransaction(User user) { - entityManager.persist(user); - return user; - } - - public User find(long id) { - return entityManager.find(User.class, id); - } -} diff --git a/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml b/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml deleted file mode 100644 index c485080879..0000000000 --- a/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml b/persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml deleted file mode 100644 index 52ef1ee685..0000000000 --- a/persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - org.h2.Driver - jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1 - sa - - - 1 - - org.hibernate.dialect.H2Dialect - - org.hibernate.cache.internal.NoCacheProvider - - true - - create - - - - - \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml b/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml deleted file mode 100644 index be564aaf5a..0000000000 --- a/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - org.h2.Driver - jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1 - sa - - - 1 - - org.hibernate.dialect.H2Dialect - - org.hibernate.cache.internal.NoCacheProvider - - true - - create - - - - - - \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java deleted file mode 100644 index f609c75834..0000000000 --- a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.hibernate.logging; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.query.Query; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.logging.Employee; - -public class HibernateLoggingIntegrationTest { - - private SessionFactory sessionFactory; - - @Before - public void setUp() throws IOException { - final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate-logging.cfg.xml") - .build(); - try { - sessionFactory = new MetadataSources(registry).buildMetadata() - .buildSessionFactory(); - Session session = sessionFactory.openSession(); - session.beginTransaction(); - session.save(new Employee("John Smith", "001")); - session.getTransaction() - .commit(); - session.close(); - } catch (Exception e) { - fail(e); - StandardServiceRegistryBuilder.destroy(registry); - } - } - - @Test - public void whenAllEmployeesAreSelected_ThenSuccess() { - Query query = sessionFactory.openSession().createQuery("from com.baeldung.hibernate.logging.Employee", Employee.class); - List deptEmployees = query.list(); - Employee deptEmployee = deptEmployees.get(0); - assertEquals("John Smith", deptEmployee.getName()); - } -} diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java deleted file mode 100644 index 4efa1e1f68..0000000000 --- a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.hibernateparameters; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.query.Query; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - -public class NamedParameterUnitTest { - private SessionFactory sessionFactory; - - @Before - public void setUp() throws Exception { - final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() - .configure() - .build(); - try { - sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); - Session session = sessionFactory.openSession(); - session.beginTransaction(); - session.save(new Event("Event 1")); - session.save(new Event("Event 2")); - session.getTransaction().commit(); - session.close(); - } catch (Exception e) { - fail(e); - StandardServiceRegistryBuilder.destroy(registry); - } - } - - @After - public void tearDown() throws Exception { - if (sessionFactory != null) { - sessionFactory.close(); - } - } - - @Test - public void whenNamedParameterProvided_thenCorrect() { - Session session = sessionFactory.openSession(); - session.beginTransaction(); - Query query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class); - - // This binds the value "Event1" to the parameter :eventTitle - query.setParameter("eventTitle", "Event 1"); - - assertEquals(1, query.list().size()); - session.getTransaction().commit(); - session.close(); - } - - @Test(expected = org.hibernate.QueryException.class) - public void whenNamedParameterMissing_thenThrowsQueryException() { - Session session = sessionFactory.openSession(); - session.beginTransaction(); - Query query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class); - - try { - query.list(); - fail("We are expecting an exception!"); - } finally { - session.getTransaction().commit(); - session.close(); - } - } -} diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java deleted file mode 100644 index b299dd5834..0000000000 --- a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.persistencecontext; - -import com.baeldung.persistencecontext.entity.User; -import com.baeldung.persistencecontext.service.ExtendedPersistenceContextUserService; -import com.baeldung.persistencecontext.service.TransctionPersistenceContextUserService; - -import javax.persistence.EntityExistsException; -import javax.persistence.TransactionRequiredException; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = com.baeldung.persistencecontext.PersistenceContextDemoApplication.class) -public class PersistenceContextIntegrationTest { - - @Autowired - private TransctionPersistenceContextUserService transctionPersistenceContext; - @Autowired - private ExtendedPersistenceContextUserService extendedPersistenceContext; - - @Test - public void testThatWhenUserSavedWithTransctionPersistenceContextThenUserShouldGetSavedInDB() { - User user = new User(121L, "Devender", "admin"); - transctionPersistenceContext.insertWithTransaction(user); - - User userFromTransctionPersistenceContext = transctionPersistenceContext.find(user.getId()); - assertNotNull(userFromTransctionPersistenceContext); - - User userFromExtendedPersistenceContext = extendedPersistenceContext.find(user.getId()); - assertNotNull(userFromExtendedPersistenceContext); - } - - @Test(expected = TransactionRequiredException.class) - public void testThatUserSaveWithoutTransactionThrowException() { - User user = new User(122L, "Devender", "admin"); - transctionPersistenceContext.insertWithoutTransaction(user); - } - - @Test - public void testThatWhenUserSavedWithExtendedPersistenceContextWithoutTransactionThenUserShouldGetCached() { - User user = new User(123L, "Devender", "admin"); - extendedPersistenceContext.insertWithoutTransaction(user); - - User userFromExtendedPersistenceContext = extendedPersistenceContext.find(user.getId()); - assertNotNull(userFromExtendedPersistenceContext); - - User userFromTransctionPersistenceContext = transctionPersistenceContext.find(user.getId()); - assertNull(userFromTransctionPersistenceContext); - } - - @Test(expected = EntityExistsException.class) - public void testThatPersistUserWithSameIdentifierThrowException() { - User user1 = new User(126L, "Devender", "admin"); - User user2 = new User(126L, "Devender", "admin"); - extendedPersistenceContext.insertWithoutTransaction(user1); - extendedPersistenceContext.insertWithoutTransaction(user2); - } - - @Test - public void testThatWhenUserSavedWithExtendedPersistenceContextWithTransactionThenUserShouldSaveEntityIntoDB() { - User user = new User(127L, "Devender", "admin"); - extendedPersistenceContext.insertWithTransaction(user); - - User userFromDB = transctionPersistenceContext.find(user.getId()); - assertNotNull(userFromDB); - } - - @Test - public void testThatWhenUserSavedWithExtendedPersistenceContextWithTransactionThenUserShouldFlushCachedEntityIntoDB() { - User user1 = new User(124L, "Devender", "admin"); - extendedPersistenceContext.insertWithoutTransaction(user1); - - User user2 = new User(125L, "Devender", "admin"); - extendedPersistenceContext.insertWithTransaction(user2); - - User user1FromTransctionPersistenceContext = transctionPersistenceContext.find(user1.getId()); - assertNotNull(user1FromTransctionPersistenceContext); - - User user2FromTransctionPersistenceContext = transctionPersistenceContext.find(user2.getId()); - assertNotNull(user2FromTransctionPersistenceContext); - } - -} diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j.xml b/persistence-modules/hibernate5-2/src/test/resources/log4j.xml deleted file mode 100644 index 2d153af124..0000000000 --- a/persistence-modules/hibernate5-2/src/test/resources/log4j.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j2.xml b/persistence-modules/hibernate5-2/src/test/resources/log4j2.xml deleted file mode 100644 index c5d0f12462..0000000000 --- a/persistence-modules/hibernate5-2/src/test/resources/log4j2.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/test/resources/logback.xml b/persistence-modules/hibernate5-2/src/test/resources/logback.xml deleted file mode 100644 index 9e591977d7..0000000000 --- a/persistence-modules/hibernate5-2/src/test/resources/logback.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - %d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n - - - - - - - - - - - - \ No newline at end of file From a5ae83d28aef770b7ef5722a56d086244369a549 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:18:27 +0530 Subject: [PATCH 03/17] JAVA-4 : Split hibernate5 module to smaller parts --- persistence-modules/hibernate5/README.md | 25 -- .../com/baeldung/hibernate/HibernateUtil.java | 28 -- .../converters/PersonNameConverter.java | 61 --- .../criteriaquery/HibernateUtil.java | 60 --- .../hibernate/criteriaquery/Student.java | 58 --- .../hibernate/customtypes/Address.java | 69 --- .../hibernate/customtypes/AddressType.java | 169 ------- .../LocalDateStringJavaDescriptor.java | 51 --- .../customtypes/LocalDateStringType.java | 34 -- .../hibernate/customtypes/OfficeEmployee.java | 88 ---- .../hibernate/customtypes/PhoneNumber.java | 43 -- .../customtypes/PhoneNumberType.java | 98 ---- .../hibernate/customtypes/Salary.java | 39 -- .../customtypes/SalaryCurrencyConvertor.java | 15 - .../hibernate/customtypes/SalaryType.java | 161 ------- .../hibernate/exception/EntityWithNoId.java | 16 - .../hibernate/exception/HibernateUtil.java | 63 --- .../baeldung/hibernate/exception/Product.java | 40 -- .../baeldung/hibernate/findall/FindAll.java | 35 -- .../baeldung/hibernate/joincolumn/Email.java | 47 -- .../baeldung/hibernate/joincolumn/Office.java | 41 -- .../hibernate/joincolumn/OfficeAddress.java | 34 -- .../joincolumn/OfficialEmployee.java | 36 -- .../jpabootstrap/application/Application.java | 34 -- .../config/HibernatePersistenceUnitInfo.java | 131 ------ .../config/JpaEntityManagerFactory.java | 69 --- .../hibernate/jpabootstrap/entities/User.java | 45 -- .../service/EmployeeSearchService.java | 15 - .../service/EmployeeSearchServiceImpl.java | 77 ---- .../hibernate/lob/HibernateSessionUtil.java | 61 --- .../baeldung/hibernate/lob/model/User.java | 46 -- .../hibernate/onetoone/HibernateUtil.java | 63 --- .../baeldung/hibernate/onetoone/Strategy.java | 25 -- .../onetoone/foreignkeybased/Address.java | 60 --- .../onetoone/foreignkeybased/User.java | 51 --- .../onetoone/jointablebased/Employee.java | 53 --- .../onetoone/jointablebased/WorkStation.java | 61 --- .../onetoone/sharedkeybased/Address.java | 60 --- .../onetoone/sharedkeybased/User.java | 50 --- .../OptimisticLockingCourse.java | 48 -- .../OptimisticLockingStudent.java | 70 --- .../hibernate/pessimisticlocking/Address.java | 34 -- .../pessimisticlocking/Customer.java | 58 --- .../pessimisticlocking/Individual.java | 49 -- .../PessimisticLockingCourse.java | 47 -- .../PessimisticLockingEmployee.java | 27 -- .../PessimisticLockingStudent.java | 46 -- .../com/baeldung/hibernate/pojo/Person.java | 32 -- .../hibernate/transaction/PostService.java | 29 -- .../hibernate/CustomClassIntegrationTest.java | 78 ---- .../DynamicMappingIntegrationTest.java | 160 ------- .../HibernateSpatialIntegrationTest.java | 161 ------- .../InheritanceMappingIntegrationTest.java | 89 ---- .../hibernate/NamedQueryIntegrationTest.java | 98 ---- .../hibernate/TemporalValuesUnitTest.java | 128 ------ .../AggregateFunctionsIntegrationTest.java | 87 ---- .../PersonNameConverterUnitTest.java | 200 --------- .../TypeSafeCriteriaIntegrationTest.java | 89 ---- .../HibernateCustomTypesManualTest.java | 90 ---- .../exception/HibernateExceptionUnitTest.java | 425 ------------------ .../hibernate/findall/FindAllUnitTest.java | 63 --- .../joincolumn/JoinColumnIntegrationTest.java | 57 --- .../EmployeeSearchServiceIntegrationTest.java | 121 ----- .../baeldung/hibernate/lob/LobUnitTest.java | 61 --- .../baeldung/hibernate/multitenancy/Car.java | 26 -- .../MultitenancyIntegrationTest.java | 104 ----- ...seApproachMultitenancyIntegrationTest.java | 25 -- .../MapMultiTenantConnectionProvider.java | 42 -- .../multitenancy/database/TenantIdNames.java | 6 - ...maApproachMultitenancyIntegrationTest.java | 26 -- .../SchemaMultiTenantConnectionProvider.java | 48 -- .../multitenancy/schema/TenantIdNames.java | 6 - ...ToOneAnnotationFKBasedIntegrationTest.java | 80 ---- ...ToOneAnnotationJTBasedIntegrationTest.java | 80 ---- ...oOneAnnotationSPKBasedIntegrationTest.java | 79 ---- .../OptimisticLockingIntegrationTest.java | 146 ------ ...asicPessimisticLockingIntegrationTest.java | 162 ------- .../PessimisticLockScopesIntegrationTest.java | 125 ------ .../QueryPlanCacheBenchmark.java | 106 ----- .../TransactionIntegrationTest.java | 57 --- .../hibernate-customtypes.properties | 14 - ...hibernate-database-multitenancy.properties | 2 - .../hibernate-database-mydb1.properties | 4 - .../hibernate-database-mydb2.properties | 4 - .../resources/hibernate-exception.properties | 16 - .../resources/hibernate-namedquery.properties | 9 - .../hibernate-pessimistic-locking.properties | 8 - .../hibernate-schema-multitenancy.properties | 7 - .../resources/hibernate-spatial.properties | 14 - 89 files changed, 5755 deletions(-) delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java delete mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java delete mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties delete mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index d1bfe897f6..7b5e3bb189 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -4,38 +4,13 @@ This module contains articles about Hibernate 5. ### Relevant articles: -- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) - [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) -- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) -- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) -- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy) -- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial) - [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor) -- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) -- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) -- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) -- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) -- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) -- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) - [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) -- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) -- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) - [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy) - [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method) -- [Custom Types in Hibernate and the @Type Annotation](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) -- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) -- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) -- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) -- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) -- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) - [[Next -->]](/hibernate5-2) \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 137fc4f0bd..11a59c9cf0 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -12,25 +12,13 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import com.baeldung.hibernate.customtypes.LocalDateStringType; -import com.baeldung.hibernate.customtypes.OfficeEmployee; import com.baeldung.hibernate.entities.DeptEmployee; -import com.baeldung.hibernate.joincolumn.Email; -import com.baeldung.hibernate.joincolumn.Office; -import com.baeldung.hibernate.joincolumn.OfficeAddress; -import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; -import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; -import com.baeldung.hibernate.pessimisticlocking.Individual; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; import com.baeldung.hibernate.pojo.Course; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; import com.baeldung.hibernate.pojo.OrderEntry; import com.baeldung.hibernate.pojo.OrderEntryIdClass; import com.baeldung.hibernate.pojo.OrderEntryPK; -import com.baeldung.hibernate.pojo.Person; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; @@ -88,7 +76,6 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(MyEmployee.class); metadataSources.addAnnotatedClass(MyProduct.class); metadataSources.addAnnotatedClass(Pen.class); - metadataSources.addAnnotatedClass(Person.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); @@ -96,26 +83,11 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class); - metadataSources.addAnnotatedClass(Individual.class); - metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); - metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); - metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); - metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); - metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); - metadataSources.addAnnotatedClass(OfficeEmployee.class); metadataSources.addAnnotatedClass(Post.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); - metadataSources.addAnnotatedClass(Email.class); - metadataSources.addAnnotatedClass(Office.class); - metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() - .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java deleted file mode 100644 index 506e674984..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.hibernate.converters; - -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; - -import com.baeldung.hibernate.pojo.PersonName; - -@Converter -public class PersonNameConverter implements AttributeConverter { - - private static final String SEPARATOR = ", "; - - @Override - public String convertToDatabaseColumn(PersonName personName) { - if (personName == null) { - return null; - } - - StringBuilder sb = new StringBuilder(); - if (personName.getSurname() != null && !personName.getSurname() - .isEmpty()) { - sb.append(personName.getSurname()); - sb.append(SEPARATOR); - } - - if (personName.getName() != null && !personName.getName() - .isEmpty()) { - sb.append(personName.getName()); - } - - return sb.toString(); - } - - @Override - public PersonName convertToEntityAttribute(String dbPersonName) { - if (dbPersonName == null || dbPersonName.isEmpty()) { - return null; - } - - String[] pieces = dbPersonName.split(SEPARATOR); - - if (pieces == null || pieces.length == 0) { - return null; - } - - PersonName personName = new PersonName(); - String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null; - if (dbPersonName.contains(SEPARATOR)) { - personName.setSurname(firstPiece); - - if (pieces.length >= 2 && pieces[1] != null && !pieces[1].isEmpty()) { - personName.setName(pieces[1]); - } - } else { - personName.setName(firstPiece); - } - - return personName; - } - -} 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 deleted file mode 100644 index 35cfe55ba6..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index 314e7ca557..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java +++ /dev/null @@ -1,58 +0,0 @@ -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/customtypes/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java deleted file mode 100644 index d559e5a6c2..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import java.util.Objects; - -public class Address { - - private String addressLine1; - private String addressLine2; - private String city; - private String country; - private int zipCode; - - public String getAddressLine1() { - return addressLine1; - } - - public String getAddressLine2() { - return addressLine2; - } - - public String getCity() { - return city; - } - - public String getCountry() { - return country; - } - - public int getZipCode() { - return zipCode; - } - - public void setAddressLine1(String addressLine1) { - this.addressLine1 = addressLine1; - } - - public void setAddressLine2(String addressLine2) { - this.addressLine2 = addressLine2; - } - - public void setCity(String city) { - this.city = city; - } - - public void setCountry(String country) { - this.country = country; - } - - public void setZipCode(int zipCode) { - this.zipCode = zipCode; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Address address = (Address) o; - return zipCode == address.zipCode && - Objects.equals(addressLine1, address.addressLine1) && - Objects.equals(addressLine2, address.addressLine2) && - Objects.equals(city, address.city) && - Objects.equals(country, address.country); - } - - @Override - public int hashCode() { - return Objects.hash(addressLine1, addressLine2, city, country, zipCode); - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java deleted file mode 100644 index c10c67df9a..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java +++ /dev/null @@ -1,169 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.IntegerType; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; -import org.hibernate.usertype.CompositeUserType; - -import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Objects; - -public class AddressType implements CompositeUserType { - - @Override - public String[] getPropertyNames() { - return new String[]{"addressLine1", "addressLine2", - "city", "country", "zipcode"}; - } - - @Override - public Type[] getPropertyTypes() { - return new Type[]{StringType.INSTANCE, StringType.INSTANCE, - StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE}; - } - - @Override - public Object getPropertyValue(Object component, int property) throws HibernateException { - - Address empAdd = (Address) component; - - switch (property) { - case 0: - return empAdd.getAddressLine1(); - case 1: - return empAdd.getAddressLine2(); - case 2: - return empAdd.getCity(); - case 3: - return empAdd.getCountry(); - case 4: - return Integer.valueOf(empAdd.getZipCode()); - } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - } - - @Override - public void setPropertyValue(Object component, int property, Object value) throws HibernateException { - - Address empAdd = (Address) component; - - switch (property) { - case 0: - empAdd.setAddressLine1((String) value); - case 1: - empAdd.setAddressLine2((String) value); - case 2: - empAdd.setCity((String) value); - case 3: - empAdd.setCountry((String) value); - case 4: - empAdd.setZipCode((Integer) value); - } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - - } - - @Override - public Class returnedClass() { - return Address.class; - } - - @Override - public boolean equals(Object x, Object y) throws HibernateException { - if (x == y) - return true; - - if (Objects.isNull(x) || Objects.isNull(y)) - return false; - - return x.equals(y); - } - - @Override - public int hashCode(Object x) throws HibernateException { - return x.hashCode(); - } - - @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - - Address empAdd = new Address(); - empAdd.setAddressLine1(rs.getString(names[0])); - - if (rs.wasNull()) - return null; - - empAdd.setAddressLine2(rs.getString(names[1])); - empAdd.setCity(rs.getString(names[2])); - empAdd.setCountry(rs.getString(names[3])); - empAdd.setZipCode(rs.getInt(names[4])); - - return empAdd; - } - - @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - - if (Objects.isNull(value)) - st.setNull(index, Types.VARCHAR); - else { - - Address empAdd = (Address) value; - st.setString(index, empAdd.getAddressLine1()); - st.setString(index + 1, empAdd.getAddressLine2()); - st.setString(index + 2, empAdd.getCity()); - st.setString(index + 3, empAdd.getCountry()); - st.setInt(index + 4, empAdd.getZipCode()); - } - } - - @Override - public Object deepCopy(Object value) throws HibernateException { - - if (Objects.isNull(value)) - return null; - - Address oldEmpAdd = (Address) value; - Address newEmpAdd = new Address(); - - newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1()); - newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2()); - newEmpAdd.setCity(oldEmpAdd.getCity()); - newEmpAdd.setCountry(oldEmpAdd.getCountry()); - newEmpAdd.setZipCode(oldEmpAdd.getZipCode()); - - return newEmpAdd; - } - - @Override - public boolean isMutable() { - return true; - } - - @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { - return (Serializable) deepCopy(value); - } - - @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return deepCopy(cached); - } - - @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return original; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java deleted file mode 100644 index 56be9e693f..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import org.hibernate.type.LocalDateType; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; -import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; -import org.hibernate.type.descriptor.java.MutabilityPlan; - -import java.time.LocalDate; - -public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { - - public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); - - public LocalDateStringJavaDescriptor() { - super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE); - } - - @Override - public String toString(LocalDate value) { - return LocalDateType.FORMATTER.format(value); - } - - @Override - public LocalDate fromString(String string) { - return LocalDate.from(LocalDateType.FORMATTER.parse(string)); - } - - @Override - public X unwrap(LocalDate value, Class type, WrapperOptions options) { - - if (value == null) - return null; - - if (String.class.isAssignableFrom(type)) - return (X) LocalDateType.FORMATTER.format(value); - - throw unknownUnwrap(type); - } - - @Override - public LocalDate wrap(X value, WrapperOptions options) { - if (value == null) - return null; - - if(String.class.isInstance(value)) - return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); - - throw unknownWrap(value.getClass()); - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java deleted file mode 100644 index c8d37073e8..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import org.hibernate.dialect.Dialect; -import org.hibernate.type.AbstractSingleColumnStandardBasicType; -import org.hibernate.type.DiscriminatorType; -import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; -import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; - -import java.time.LocalDate; - -public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { - - public static final LocalDateStringType INSTANCE = new LocalDateStringType(); - - public LocalDateStringType() { - super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); - } - - @Override - public String getName() { - return "LocalDateString"; - } - - @Override - public LocalDate stringToObject(String xml) throws Exception { - return fromString(xml); - } - - @Override - public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { - return '\'' + toString(value) + '\''; - } - -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java deleted file mode 100644 index 3ca06e4316..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import com.baeldung.hibernate.pojo.Phone; -import org.hibernate.annotations.Columns; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import java.time.LocalDate; - -@TypeDef(name = "PhoneNumber", - typeClass = PhoneNumberType.class, - defaultForType = PhoneNumber.class) -@Entity -@Table(name = "OfficeEmployee") -public class OfficeEmployee { - - @Id - @GeneratedValue - private long id; - - @Column - @Type(type = "LocalDateString") - private LocalDate dateOfJoining; - - @Columns(columns = {@Column(name = "country_code"), - @Column(name = "city_code"), - @Column(name = "number")}) - private PhoneNumber employeeNumber; - - @Columns(columns = {@Column(name = "address_line_1"), - @Column(name = "address_line_2"), - @Column(name = "city"), @Column(name = "country"), - @Column(name = "zip_code")}) - @Type(type = "com.baeldung.hibernate.customtypes.AddressType") - private Address empAddress; - - @Type(type = "com.baeldung.hibernate.customtypes.SalaryType", - parameters = {@Parameter(name = "currency", value = "USD")}) - @Columns(columns = {@Column(name = "amount"), - @Column(name = "currency")}) - private Salary salary; - - public Salary getSalary() { - return salary; - } - - public void setSalary(Salary salary) { - this.salary = salary; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public LocalDate getDateOfJoining() { - return dateOfJoining; - } - - public void setDateOfJoining(LocalDate dateOfJoining) { - this.dateOfJoining = dateOfJoining; - } - - public PhoneNumber getEmployeeNumber() { - return employeeNumber; - } - - public void setEmployeeNumber(PhoneNumber employeeNumber) { - this.employeeNumber = employeeNumber; - } - - public Address getEmpAddress() { - return empAddress; - } - - public void setEmpAddress(Address empAddress) { - this.empAddress = empAddress; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java deleted file mode 100644 index 0be6cbc910..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import java.util.Objects; - -public final class PhoneNumber { - - private final int countryCode; - private final int cityCode; - private final int number; - - public PhoneNumber(int countryCode, int cityCode, int number) { - this.countryCode = countryCode; - this.cityCode = cityCode; - this.number = number; - } - - public int getCountryCode() { - return countryCode; - } - - public int getCityCode() { - return cityCode; - } - - public int getNumber() { - return number; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PhoneNumber that = (PhoneNumber) o; - return countryCode == that.countryCode && - cityCode == that.cityCode && - number == that.number; - } - - @Override - public int hashCode() { - return Objects.hash(countryCode, cityCode, number); - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java deleted file mode 100644 index 9f09352bec..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.usertype.UserType; - -import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Objects; - - -public class PhoneNumberType implements UserType { - @Override - public int[] sqlTypes() { - return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER}; - } - - @Override - public Class returnedClass() { - return PhoneNumber.class; - } - - @Override - public boolean equals(Object x, Object y) throws HibernateException { - if (x == y) - return true; - if (Objects.isNull(x) || Objects.isNull(y)) - return false; - - return x.equals(y); - } - - @Override - public int hashCode(Object x) throws HibernateException { - return x.hashCode(); - } - - @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - int countryCode = rs.getInt(names[0]); - - if (rs.wasNull()) - return null; - - int cityCode = rs.getInt(names[1]); - int number = rs.getInt(names[2]); - PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number); - - return employeeNumber; - } - - @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - - if (Objects.isNull(value)) { - st.setNull(index, Types.INTEGER); - } else { - PhoneNumber employeeNumber = (PhoneNumber) value; - st.setInt(index,employeeNumber.getCountryCode()); - st.setInt(index+1,employeeNumber.getCityCode()); - st.setInt(index+2,employeeNumber.getNumber()); - } - } - - @Override - public Object deepCopy(Object value) throws HibernateException { - if (Objects.isNull(value)) - return null; - - PhoneNumber empNumber = (PhoneNumber) value; - PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber()); - - return newEmpNumber; - } - - @Override - public boolean isMutable() { - return false; - } - - @Override - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable) value; - } - - @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; - } - - @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java deleted file mode 100644 index f9a7ac5902..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import java.util.Objects; - -public class Salary { - - private Long amount; - private String currency; - - public Long getAmount() { - return amount; - } - - public void setAmount(Long amount) { - this.amount = amount; - } - - public String getCurrency() { - return currency; - } - - public void setCurrency(String currency) { - this.currency = currency; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Salary salary = (Salary) o; - return Objects.equals(amount, salary.amount) && - Objects.equals(currency, salary.currency); - } - - @Override - public int hashCode() { - return Objects.hash(amount, currency); - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java deleted file mode 100644 index 340c697c11..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -public class SalaryCurrencyConvertor { - - public static Long convert(Long amount, String oldCurr, String newCurr){ - if (newCurr.equalsIgnoreCase(oldCurr)) - return amount; - - return convertTo(); - } - - private static Long convertTo() { - return 10L; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java deleted file mode 100644 index 266b85140b..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.LongType; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; -import org.hibernate.usertype.CompositeUserType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Objects; -import java.util.Properties; - -public class SalaryType implements CompositeUserType, DynamicParameterizedType { - - private String localCurrency; - - @Override - public String[] getPropertyNames() { - return new String[]{"amount", "currency"}; - } - - @Override - public Type[] getPropertyTypes() { - return new Type[]{LongType.INSTANCE, StringType.INSTANCE}; - } - - @Override - public Object getPropertyValue(Object component, int property) throws HibernateException { - - Salary salary = (Salary) component; - - switch (property) { - case 0: - return salary.getAmount(); - case 1: - return salary.getCurrency(); - } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - - } - - - @Override - public void setPropertyValue(Object component, int property, Object value) throws HibernateException { - - Salary salary = (Salary) component; - - switch (property) { - case 0: - salary.setAmount((Long) value); - case 1: - salary.setCurrency((String) value); - } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - - } - - @Override - public Class returnedClass() { - return Salary.class; - } - - @Override - public boolean equals(Object x, Object y) throws HibernateException { - - if (x == y) - return true; - - if (Objects.isNull(x) || Objects.isNull(y)) - return false; - - return x.equals(y); - - } - - @Override - public int hashCode(Object x) throws HibernateException { - return x.hashCode(); - } - - @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - - Salary salary = new Salary(); - salary.setAmount(rs.getLong(names[0])); - - if (rs.wasNull()) - return null; - - salary.setCurrency(rs.getString(names[1])); - - return salary; - } - - @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - - - if (Objects.isNull(value)) - st.setNull(index, Types.BIGINT); - else { - - Salary salary = (Salary) value; - st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(), - salary.getCurrency(), localCurrency)); - st.setString(index + 1, salary.getCurrency()); - } - } - - @Override - public Object deepCopy(Object value) throws HibernateException { - - if (Objects.isNull(value)) - return null; - - Salary oldSal = (Salary) value; - Salary newSal = new Salary(); - - newSal.setAmount(oldSal.getAmount()); - newSal.setCurrency(oldSal.getCurrency()); - - return newSal; - } - - @Override - public boolean isMutable() { - return true; - } - - @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { - return (Serializable) deepCopy(value); - } - - @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return deepCopy(cached); - } - - @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return original; - } - - @Override - public void setParameterValues(Properties parameters) { - this.localCurrency = parameters.getProperty("currency"); - } -} 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 deleted file mode 100644 index 989fa1281a..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ae5174ac9c..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index 031fa38de0..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java +++ /dev/null @@ -1,40 +0,0 @@ -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/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java deleted file mode 100644 index cc0c234df0..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.hibernate.findall; - -import java.util.List; - -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -import org.hibernate.Session; - -import com.baeldung.hibernate.pojo.Student; - -public class FindAll { - - private Session session; - - public FindAll(Session session) { - super(); - this.session = session; - } - - public List findAllWithJpql() { - return session.createQuery("SELECT a FROM Student a", Student.class).getResultList(); - } - - public List findAllWithCriteriaQuery() { - CriteriaBuilder cb = session.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(Student.class); - Root rootEntry = cq.from(Student.class); - CriteriaQuery all = cq.select(rootEntry); - TypedQuery allQuery = session.createQuery(all); - return allQuery.getResultList(); - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java deleted file mode 100644 index df07c3cf69..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.hibernate.joincolumn; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -@Entity -public class Email { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String address; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "employee_id") - private OfficialEmployee employee; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public OfficialEmployee getEmployee() { - return employee; - } - - public void setEmployee(OfficialEmployee employee) { - this.employee = employee; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java deleted file mode 100644 index 9940577761..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.hibernate.joincolumn; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.ManyToOne; - -@Entity -public class Office { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumns({ - @JoinColumn(name="ADDR_ID", referencedColumnName="ID"), - @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP") - }) - private OfficeAddress address; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public OfficeAddress getAddress() { - return address; - } - - public void setAddress(OfficeAddress address) { - this.address = address; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java deleted file mode 100644 index cc723db6a2..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.hibernate.joincolumn; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class OfficeAddress { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(name = "ZIP") - private String zipCode; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java deleted file mode 100644 index 49c63c7578..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.hibernate.joincolumn; - -import java.util.List; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; - -@Entity -public class OfficialEmployee { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee") - private List emails; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public List getEmails() { - return emails; - } - - public void setEmails(List emails) { - this.emails = emails; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java deleted file mode 100644 index f7b8e6bf6d..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.hibernate.jpabootstrap.application; - -import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory; -import com.baeldung.hibernate.jpabootstrap.entities.User; -import javax.persistence.EntityManager; - -public class Application { - - public static void main(String[] args) { - EntityManager entityManager = getJpaEntityManager(); - User user = entityManager.find(User.class, 1); - System.out.println(user); - entityManager.getTransaction().begin(); - user.setName("John"); - user.setEmail("john@domain.com"); - entityManager.merge(user); - entityManager.getTransaction().commit(); - entityManager.getTransaction().begin(); - entityManager.persist(new User("Monica", "monica@domain.com")); - entityManager.getTransaction().commit(); - - // additional CRUD operations - - } - - private static class EntityManagerHolder { - private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory( - new Class[]{User.class}).getEntityManager(); - } - - public static EntityManager getJpaEntityManager() { - return EntityManagerHolder.ENTITY_MANAGER; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java deleted file mode 100644 index 3852b44b64..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.baeldung.hibernate.jpabootstrap.config; - -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import javax.sql.DataSource; -import javax.persistence.SharedCacheMode; -import javax.persistence.ValidationMode; -import javax.persistence.spi.ClassTransformer; -import javax.persistence.spi.PersistenceUnitInfo; -import javax.persistence.spi.PersistenceUnitTransactionType; -import org.hibernate.jpa.HibernatePersistenceProvider; - -public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo { - - public static final String JPA_VERSION = "2.1"; - private final String persistenceUnitName; - private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; - private final List managedClassNames; - private final List mappingFileNames = new ArrayList<>(); - private final Properties properties; - private DataSource jtaDataSource; - private DataSource nonjtaDataSource; - private final List transformers = new ArrayList<>(); - - public HibernatePersistenceUnitInfo(String persistenceUnitName, List managedClassNames, Properties properties) { - this.persistenceUnitName = persistenceUnitName; - this.managedClassNames = managedClassNames; - this.properties = properties; - } - - @Override - public String getPersistenceUnitName() { - return persistenceUnitName; - } - - @Override - public String getPersistenceProviderClassName() { - return HibernatePersistenceProvider.class.getName(); - } - - @Override - public PersistenceUnitTransactionType getTransactionType() { - return transactionType; - } - - public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) { - this.jtaDataSource = jtaDataSource; - this.nonjtaDataSource = null; - transactionType = PersistenceUnitTransactionType.JTA; - return this; - } - - @Override - public DataSource getJtaDataSource() { - return jtaDataSource; - } - - public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) { - this.nonjtaDataSource = nonJtaDataSource; - this.jtaDataSource = null; - transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; - return this; - } - - @Override - public DataSource getNonJtaDataSource() { - return nonjtaDataSource; - } - - @Override - public List getMappingFileNames() { - return mappingFileNames; - } - - @Override - public List getJarFileUrls() { - return Collections.emptyList(); - } - - @Override - public URL getPersistenceUnitRootUrl() { - return null; - } - - @Override - public List getManagedClassNames() { - return managedClassNames; - } - - @Override - public boolean excludeUnlistedClasses() { - return false; - } - - @Override - public SharedCacheMode getSharedCacheMode() { - return SharedCacheMode.UNSPECIFIED; - } - - @Override - public ValidationMode getValidationMode() { - return ValidationMode.AUTO; - } - - public Properties getProperties() { - return properties; - } - - @Override - public String getPersistenceXMLSchemaVersion() { - return JPA_VERSION; - } - - @Override - public ClassLoader getClassLoader() { - return Thread.currentThread().getContextClassLoader(); - } - - @Override - public void addTransformer(ClassTransformer transformer) { - transformers.add(transformer); - } - - @Override - public ClassLoader getNewTempClassLoader() { - return null; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java deleted file mode 100644 index bc1932af6f..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.hibernate.jpabootstrap.config; - -import com.mysql.cj.jdbc.MysqlDataSource; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.sql.DataSource; -import javax.persistence.EntityManagerFactory; -import javax.persistence.spi.PersistenceUnitInfo; -import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; -import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; - -public class JpaEntityManagerFactory { - - private final String DB_URL = "jdbc:mysql://databaseurl"; - private final String DB_USER_NAME = "username"; - private final String DB_PASSWORD = "password"; - private final Class[] entityClasses; - - public JpaEntityManagerFactory(Class[] entityClasses) { - this.entityClasses = entityClasses; - } - - public EntityManager getEntityManager() { - return getEntityManagerFactory().createEntityManager(); - } - - protected EntityManagerFactory getEntityManagerFactory() { - PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName()); - Map configuration = new HashMap<>(); - return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration) - .build(); - } - - protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) { - return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties()); - } - - protected List getEntityClassNames() { - return Arrays.asList(getEntities()) - .stream() - .map(Class::getName) - .collect(Collectors.toList()); - } - - protected Properties getProperties() { - Properties properties = new Properties(); - properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); - properties.put("hibernate.id.new_generator_mappings", false); - properties.put("hibernate.connection.datasource", getMysqlDataSource()); - return properties; - } - - protected Class[] getEntities() { - return entityClasses; - } - - protected DataSource getMysqlDataSource() { - MysqlDataSource mysqlDataSource = new MysqlDataSource(); - mysqlDataSource.setURL(DB_URL); - mysqlDataSource.setUser(DB_USER_NAME); - mysqlDataSource.setPassword(DB_PASSWORD); - return mysqlDataSource; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java deleted file mode 100644 index 86ca1dfa19..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.hibernate.jpabootstrap.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - private String name; - private String email; - - public User(){} - - public User(String name, String email) { - this.name = name; - this.email = email; - } - - public void setName(String name) { - this.name = name; - } - - public void setEmail(String email) { - this.email = email; - } - - public long getId() { - return id; - } - - public String getName() { - return name; - } - - public String getEmail() { - return email; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java deleted file mode 100644 index b7d1a537f0..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.hibernate.jpacriteriabuilder.service; - -import java.util.List; - -import com.baeldung.hibernate.entities.DeptEmployee; - -public interface EmployeeSearchService { - - List filterbyTitleUsingCriteriaBuilder(List titles); - - List filterbyTitleUsingExpression(List titles); - - List searchByDepartmentQuery(String query); - -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java deleted file mode 100644 index e79168a451..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baeldung.hibernate.jpacriteriabuilder.service; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaBuilder.In; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import javax.persistence.criteria.Subquery; - -import com.baeldung.hibernate.entities.Department; -import com.baeldung.hibernate.entities.DeptEmployee; - -public class EmployeeSearchServiceImpl implements EmployeeSearchService { - - private EntityManager entityManager; - private CriteriaBuilder criteriaBuilder; - - public EmployeeSearchServiceImpl(EntityManager entityManager) { - this.entityManager = entityManager; - this.criteriaBuilder = entityManager.getCriteriaBuilder(); - - } - - @Override - public List filterbyTitleUsingCriteriaBuilder(List titles) { - CriteriaQuery criteriaQuery = createCriteriaQuery(DeptEmployee.class); - Root root = criteriaQuery.from(DeptEmployee.class); - In inClause = criteriaBuilder.in(root.get("title")); - for (String title : titles) { - inClause.value(title); - } - criteriaQuery.select(root) - .where(inClause); - TypedQuery query = entityManager.createQuery(criteriaQuery); - return query.getResultList(); - } - - @Override - public List filterbyTitleUsingExpression(List titles) { - CriteriaQuery criteriaQuery = createCriteriaQuery(DeptEmployee.class); - Root root = criteriaQuery.from(DeptEmployee.class); - criteriaQuery.select(root) - .where(root.get("title") - .in(titles)); - TypedQuery query = entityManager.createQuery(criteriaQuery); - return query.getResultList(); - } - - @Override - public List searchByDepartmentQuery(String searchKey) { - CriteriaQuery criteriaQuery = createCriteriaQuery(DeptEmployee.class); - Root emp = criteriaQuery.from(DeptEmployee.class); - - Subquery subquery = criteriaQuery.subquery(Department.class); - Root dept = subquery.from(Department.class); - subquery.select(dept) - .distinct(true) - .where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey) - .append("%") - .toString())); - - criteriaQuery.select(emp) - .where(criteriaBuilder.in(emp.get("department")) - .value(subquery)); - - TypedQuery query = entityManager.createQuery(criteriaQuery); - return query.getResultList(); - } - - private CriteriaQuery createCriteriaQuery(Class klass) { - return criteriaBuilder.createQuery(klass); - } - -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java deleted file mode 100644 index dc5242ee7c..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.hibernate.lob; - -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; - -import com.baeldung.hibernate.lob.model.User; - -public class HibernateSessionUtil { - - 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(User.class); - - Metadata metadata = metadataSources.buildMetadata(); - 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.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/lob/model/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java deleted file mode 100644 index 21f725b388..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.hibernate.lob.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.Table; - -@Entity -@Table(name="user") -public class User { - - @Id - private String id; - - @Column(name = "name", columnDefinition="VARCHAR(128)") - private String name; - - @Lob - @Column(name = "photo", columnDefinition="BLOB") - private byte[] photo; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public byte[] getPhoto() { - return photo; - } - - public void setPhoto(byte[] photo) { - this.photo = photo; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java deleted file mode 100644 index c2f276472e..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.hibernate.onetoone; - -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(Strategy strategy) { - return buildSessionFactory(strategy); - } - - private static SessionFactory buildSessionFactory(Strategy strategy) { - try { - ServiceRegistry serviceRegistry = configureServiceRegistry(); - - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - - for (Class entityClass : strategy.getEntityClasses()) { - metadataSources.addAnnotatedClass(entityClass); - } - - 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/onetoone/Strategy.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java deleted file mode 100644 index 3180566ca5..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.hibernate.onetoone; - - -import java.util.Arrays; -import java.util.List; - -public enum Strategy { - //See that the classes belongs to different packages - FOREIGN_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.foreignkeybased.User.class, - com.baeldung.hibernate.onetoone.foreignkeybased.Address.class)), - SHARED_PRIMARY_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.sharedkeybased.User.class, - com.baeldung.hibernate.onetoone.sharedkeybased.Address.class)), - JOIN_TABLE_BASED(Arrays.asList(com.baeldung.hibernate.onetoone.jointablebased.Employee.class, - com.baeldung.hibernate.onetoone.jointablebased.WorkStation.class)); - - private List> entityClasses; - - Strategy(List> entityClasses) { - this.entityClasses = entityClasses; - } - - public List> getEntityClasses() { - return entityClasses; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java deleted file mode 100644 index e05eb46030..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.hibernate.onetoone.foreignkeybased; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "address") -public class Address { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private Long id; - - @Column(name = "street") - private String street; - - @Column(name = "city") - private String city; - - @OneToOne(mappedBy = "address") - private User user; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java deleted file mode 100644 index dda972f29c..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.hibernate.onetoone.foreignkeybased; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private Long id; - - @Column(name = "username") - private String userName; - - @OneToOne(cascade = CascadeType.ALL) - @JoinColumn(name = "address_id", referencedColumnName = "id") - private Address address; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java deleted file mode 100644 index a0bc101b9f..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.hibernate.onetoone.jointablebased; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "employee") -public class Employee { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private Long id; - - @Column(name = "ename") - private String name; - - @OneToOne(cascade = CascadeType.ALL) - @JoinTable(name = "emp_workstation", joinColumns = {@JoinColumn(name = "employee_id", referencedColumnName = "id")}, - inverseJoinColumns = {@JoinColumn(name = "workstation_id", referencedColumnName = "id")}) - private WorkStation workStation; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public WorkStation getWorkStation() { - return workStation; - } - - public void setWorkStation(WorkStation workStation) { - this.workStation = workStation; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java deleted file mode 100644 index f530611f6e..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.hibernate.onetoone.jointablebased; - - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "workstation") -public class WorkStation { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private Long id; - - @Column(name = "workstation_number") - private Integer workstationNumber; - - @Column(name = "floor") - private String floor; - - @OneToOne(mappedBy = "workStation") - private Employee employee; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Integer getWorkstationNumber() { - return workstationNumber; - } - - public void setWorkstationNumber(Integer workstationNumber) { - this.workstationNumber = workstationNumber; - } - - public String getFloor() { - return floor; - } - - public void setFloor(String floor) { - this.floor = floor; - } - - public Employee getEmployee() { - return employee; - } - - public void setEmployee(Employee employee) { - this.employee = employee; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java deleted file mode 100644 index 927516f6bb..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.hibernate.onetoone.sharedkeybased; - - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.MapsId; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "address") -public class Address { - - @Id - @Column(name = "id") - private Long id; - - @Column(name = "street") - private String street; - - @Column(name = "city") - private String city; - - @OneToOne - @MapsId - private User user; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java deleted file mode 100644 index fa00db1271..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.hibernate.onetoone.sharedkeybased; - - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private Long id; - - @Column(name = "username") - private String userName; - - @OneToOne(mappedBy = "user", cascade = CascadeType.ALL) - private Address address; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java deleted file mode 100644 index 1af3e3e21b..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.hibernate.optimisticlocking; - -import javax.persistence.*; - -@Entity -public class OptimisticLockingCourse { - - @Id - private Long id; - - private String name; - - @ManyToOne - @JoinTable(name = "optimistic_student_course") - private OptimisticLockingStudent student; - - public OptimisticLockingCourse(Long id, String name) { - this.id = id; - this.name = name; - } - - public OptimisticLockingCourse() { - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public OptimisticLockingStudent getStudent() { - return student; - } - - public void setStudent(OptimisticLockingStudent student) { - this.student = student; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java deleted file mode 100644 index b79212ae8d..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.hibernate.optimisticlocking; - -import javax.persistence.*; -import java.util.List; - -@Entity -public class OptimisticLockingStudent { - - @Id - private Long id; - - private String name; - - private String lastName; - @Version - private Integer version; - - @OneToMany(mappedBy = "student") - private List courses; - - public OptimisticLockingStudent(Long id, String name, String lastName, List courses) { - this.id = id; - this.name = name; - this.lastName = lastName; - this.courses = courses; - } - - public OptimisticLockingStudent() { - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Integer getVersion() { - return version; - } - - public void setVersion(Integer version) { - this.version = version; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public List getCourses() { - return courses; - } - - public void setCourses(List courses) { - this.courses = courses; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java deleted file mode 100644 index c889cb6127..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import javax.persistence.Embeddable; - -@Embeddable -public class Address { - - private String country; - private String city; - - public Address(String country, String city) { - this.country = country; - this.city = city; - } - - public Address() { - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java deleted file mode 100644 index cb73cbc958..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import javax.persistence.*; -import java.util.List; - -@Entity -public class Customer { - - @Id - private Long customerId; - private String name; - private String lastName; - @ElementCollection - @CollectionTable(name = "customer_address") - private List
addressList; - - public Customer() { - } - - public Customer(Long customerId, String name, String lastName, List
addressList) { - this.customerId = customerId; - this.name = name; - this.lastName = lastName; - this.addressList = addressList; - } - - public Long getCustomerId() { - return customerId; - } - - public void setCustomerId(Long customerId) { - this.customerId = customerId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public List
getAddressList() { - return addressList; - } - - public void setAddressList(List
addressList) { - this.addressList = addressList; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java deleted file mode 100644 index e491c09eb5..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; - -@Entity -@Inheritance(strategy = InheritanceType.JOINED) -public class Individual { - - @Id - private Long id; - private String name; - private String lastName; - - public Individual(Long id, String name, String lastName) { - this.id = id; - this.name = name; - this.lastName = lastName; - } - - public Individual() { - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java deleted file mode 100644 index aea7d5fc87..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import javax.persistence.*; - -@Entity -public class PessimisticLockingCourse { - - @Id - private Long courseId; - private String name; - @ManyToOne - @JoinTable(name = "student_course") - private PessimisticLockingStudent student; - - public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) { - this.courseId = courseId; - this.name = name; - this.student = student; - } - - public PessimisticLockingCourse() { - } - - public Long getCourseId() { - return courseId; - } - - public void setCourseId(Long courseId) { - this.courseId = courseId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public PessimisticLockingStudent getStudent() { - return student; - } - - public void setStudent(PessimisticLockingStudent students) { - this.student = students; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java deleted file mode 100644 index a1328cbdad..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import javax.persistence.Entity; -import java.math.BigDecimal; - -@Entity -public class PessimisticLockingEmployee extends Individual { - - private BigDecimal salary; - - public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) { - super(id, name, lastName); - this.salary = salary; - } - - public PessimisticLockingEmployee() { - super(); - } - - public BigDecimal getSalary() { - return salary; - } - - public void setSalary(BigDecimal average) { - this.salary = average; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java deleted file mode 100644 index e6c5f476b4..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import javax.persistence.*; -import java.util.List; - -@Entity -public class PessimisticLockingStudent { - - @Id - private Long id; - private String name; - @OneToMany(mappedBy = "student") - private List courses; - - public PessimisticLockingStudent(Long id, String name) { - this.id = id; - this.name = name; - } - - public PessimisticLockingStudent() { - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getCourses() { - return courses; - } - - public void setCourses(List courses) { - this.courses = courses; - } -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java deleted file mode 100644 index 390a5954ed..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.hibernate.pojo; - -import javax.persistence.Convert; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -import com.baeldung.hibernate.converters.PersonNameConverter; - -@Entity(name = "PersonTable") -public class Person { - - @Id - @GeneratedValue - private Long id; - - @Convert(converter = PersonNameConverter.class) - private PersonName personName; - - public PersonName getPersonName() { - return personName; - } - - public void setPersonName(PersonName personName) { - this.personName = personName; - } - - public Long getId() { - return id; - } - -} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java deleted file mode 100644 index 5a4eb20079..0000000000 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.hibernate.transaction; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.query.Query; - -public class PostService { - - - private Session session; - - public PostService(Session session) { - this.session = session; - } - - - public void updatePost(String title, String body, int id) { - Transaction txn = session.beginTransaction(); - Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3"); - updateQuery.setParameter(1, title); - updateQuery.setParameter(2, body); - updateQuery.setParameter(3, id); - updateQuery.executeUpdate(); - txn.commit(); - } - - - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java deleted file mode 100644 index 699890c457..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.hibernate; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.util.List; - -import com.baeldung.hibernate.entities.DeptEmployee; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.query.Query; -import org.hibernate.transform.Transformers; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import com.baeldung.hibernate.entities.Department; -import com.baeldung.hibernate.pojo.Result; - -public class CustomClassIntegrationTest { - - private Session session; - - private Transaction transaction; - - @BeforeEach - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory().openSession(); - transaction = session.beginTransaction(); - session.createNativeQuery("delete from department").executeUpdate(); - Department department = new Department("Sales"); - DeptEmployee employee = new DeptEmployee("John Smith", "001", department); - session.persist(department); - session.persist(employee); - transaction.commit(); - transaction = session.beginTransaction(); - } - - @Test - public void whenAllManagersAreSelected_ThenObjectGraphIsReturned() { - Query query = session.createQuery("from com.baeldung.hibernate.entities.DeptEmployee"); - List deptEmployees = query.list(); - DeptEmployee deptEmployee = deptEmployees.get(0); - assertEquals("John Smith", deptEmployee.getName()); - assertEquals("Sales", deptEmployee.getDepartment().getName()); - } - - @Test - public void whenIndividualPropertiesAreSelected_ThenObjectArrayIsReturned() { - Query query = session.createQuery("select m.name, m.department.name from com.baeldung.hibernate.entities.DeptEmployee m"); - List managers = query.list(); - Object[] manager = (Object[]) managers.get(0); - assertEquals("John Smith", manager[0]); - assertEquals("Sales", manager[1]); - } - - @Test - public void whenResultConstructorInSelect_ThenListOfResultIsReturned() { - Query query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) " - + "from DeptEmployee m"); - List results = query.list(); - Result result = results.get(0); - assertEquals("John Smith", result.getEmployeeName()); - assertEquals("Sales", result.getDepartmentName()); - } - - @Test - public void whenResultTransformerOnQuery_ThenListOfResultIsReturned() { - Query query = session.createQuery("select m.name as employeeName, m.department.name as departmentName " - + "from com.baeldung.hibernate.entities.DeptEmployee m"); - query.setResultTransformer(Transformers.aliasToBean(Result.class)); - List results = query.list(); - Result result = results.get(0); - assertEquals("John Smith", result.getEmployeeName()); - assertEquals("Sales", result.getDepartmentName()); - } - - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java deleted file mode 100644 index 7a112200b5..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.baeldung.hibernate; - -import com.baeldung.hibernate.pojo.Employee; -import com.baeldung.hibernate.pojo.EntityDescription; -import com.baeldung.hibernate.pojo.Phone; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DynamicMappingIntegrationTest { - - private Session session; - - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory().openSession(); - transaction = session.beginTransaction(); - - session.createNativeQuery("delete from phone").executeUpdate(); - session.createNativeQuery("delete from employee").executeUpdate(); - - transaction.commit(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() { - Employee employee = new Employee(10_000L, 25); - assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L); - - session.save(employee); - session.flush(); - session.clear(); - - employee = session.get(Employee.class, employee.getId()); - assertThat(employee.getTax()).isEqualTo(2_500L); - } - - @Test - public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { - Employee employee = new Employee(); - - session.save(employee); - session.clear(); - - employee = session.find(Employee.class, employee.getId()); - assertThat(employee).isNotNull(); - - employee.setDeleted(true); - session.flush(); - - employee = session.find(Employee.class, employee.getId()); - assertThat(employee).isNotNull(); - - session.clear(); - - employee = session.find(Employee.class, employee.getId()); - assertThat(employee).isNull(); - - } - - @Test - public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { - Employee employee = new Employee(); - Phone phone1 = new Phone("555-45-67"); - Phone phone2 = new Phone("555-89-01"); - employee.getPhones().add(phone1); - employee.getPhones().add(phone2); - - session.save(phone1); - session.save(phone2); - session.save(employee); - session.flush(); - session.clear(); - - employee = session.find(Employee.class, employee.getId()); - assertThat(employee.getPhones()).hasSize(2); - - employee.getPhones().iterator().next().setDeleted(true); - session.flush(); - session.clear(); - - employee = session.find(Employee.class, employee.getId()); - assertThat(employee.getPhones()).hasSize(1); - - List fullPhoneList = session.createQuery("from Phone").getResultList(); - assertThat(fullPhoneList).hasSize(2); - - } - - @Test - public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException { - session.save(new Employee(10_000, 25)); - session.save(new Employee(12_000, 25)); - session.save(new Employee(15_000, 25)); - - session.flush(); - session.clear(); - - session.enableFilter("incomeLevelFilter") - .setParameter("incomeLimit", 11_000); - - List employees = session.createQuery("from Employee").getResultList(); - - assertThat(employees).hasSize(2); - - Employee employee = session.get(Employee.class, 1); - assertThat(employee.getGrossIncome()).isEqualTo(10_000); - - session.disableFilter("incomeLevelFilter"); - employees = session.createQuery("from Employee").getResultList(); - - assertThat(employees).hasSize(3); - - } - - @Test - public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() { - Employee employee = new Employee(); - Phone phone1 = new Phone("555-45-67"); - Phone phone2 = new Phone("555-89-01"); - employee.getPhones().add(phone1); - employee.getPhones().add(phone2); - - EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee); - EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1); - EntityDescription phone2Description = new EntityDescription("Work phone", phone1); - - session.save(phone1); - session.save(phone2); - session.save(employee); - session.save(employeeDescription); - session.save(phone1Description); - session.save(phone2Description); - session.flush(); - session.clear(); - - List descriptions = session.createQuery("from EntityDescription").getResultList(); - - assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue(); - assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue(); - assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue(); - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java deleted file mode 100644 index 74f752ab8c..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.baeldung.hibernate; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.util.Properties; - -import javax.persistence.Query; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.pojo.PointEntity; -import com.baeldung.hibernate.pojo.PolygonEntity; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.Point; -import com.vividsolutions.jts.geom.Polygon; -import com.vividsolutions.jts.io.ParseException; -import com.vividsolutions.jts.io.WKTReader; -import com.vividsolutions.jts.util.GeometricShapeFactory; - -import geodb.GeoDB; - -public class HibernateSpatialIntegrationTest { - - private Session session; - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") - .openSession(); - transaction = session.beginTransaction(); - session.doWork(conn -> { GeoDB.InitGeoDB(conn); }); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void shouldConvertWktToGeometry() throws ParseException { - Geometry geometry = wktToGeometry("POINT (2 5)"); - assertEquals("Point", geometry.getGeometryType()); - assertTrue(geometry instanceof Point); - } - - @Test - public void shouldInsertAndSelectPoints() throws ParseException { - PointEntity entity = new PointEntity(); - entity.setPoint((Point) wktToGeometry("POINT (1 1)")); - - session.persist(entity); - PointEntity fromDb = session.find(PointEntity.class, entity.getId()); - assertEquals("POINT (1 1)", fromDb.getPoint().toString()); - } - - @Test - public void shouldSelectDisjointPoints() throws ParseException { - insertPoint("POINT (1 2)"); - insertPoint("POINT (3 4)"); - insertPoint("POINT (5 6)"); - - Point point = (Point) wktToGeometry("POINT (3 4)"); - Query query = session.createQuery("select p from PointEntity p " - + "where disjoint(p.point, :point) = true", PointEntity.class); - query.setParameter("point", point); - assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString()); - assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString()); - } - - @Test - public void shouldSelectAllPointsWithinPolygon() throws ParseException { - insertPoint("POINT (1 1)"); - insertPoint("POINT (1 2)"); - insertPoint("POINT (3 4)"); - insertPoint("POINT (5 6)"); - - Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true", - PointEntity.class); - query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))")); - assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) - .containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)"); - } - - @Test - public void shouldSelectAllPointsWithinRadius() throws ParseException { - insertPoint("POINT (1 1)"); - insertPoint("POINT (1 2)"); - insertPoint("POINT (3 4)"); - insertPoint("POINT (5 6)"); - - Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true", - PointEntity.class); - query.setParameter("circle", createCircle(0.0, 0.0, 5)); - - assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) - .containsOnly("POINT (1 1)", "POINT (1 2)"); - } - - @Test - public void shouldSelectAdjacentPolygons() throws ParseException { - insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))"); - insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); - insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))"); - - Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true", - PolygonEntity.class); - query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))")); - assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString())) - .containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); - } - - private void insertPoint(String point) throws ParseException { - PointEntity entity = new PointEntity(); - entity.setPoint((Point) wktToGeometry(point)); - session.persist(entity); - } - - private void insertPolygon(String polygon) throws ParseException { - PolygonEntity entity = new PolygonEntity(); - entity.setPolygon((Polygon) wktToGeometry(polygon)); - session.persist(entity); - } - - private Geometry wktToGeometry(String wellKnownText) throws ParseException { - WKTReader fromText = new WKTReader(); - Geometry geom = null; - geom = fromText.read(wellKnownText); - return geom; - } - - private static Geometry createCircle(double x, double y, double radius) { - GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); - shapeFactory.setNumPoints(32); - shapeFactory.setCentre(new Coordinate(x, y)); - shapeFactory.setSize(radius * 2); - return shapeFactory.createCircle(); - } - - public static Properties getProperties(String propertyFile) throws IOException { - Properties properties = new Properties(); - URL propertiesURL = Thread.currentThread() - .getContextClassLoader() - .getResource(propertyFile); - try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { - properties.load(inputStream); - } - return properties; - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java deleted file mode 100644 index 0f35dbb8af..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.baeldung.hibernate; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.pojo.inheritance.Bag; -import com.baeldung.hibernate.pojo.inheritance.Book; -import com.baeldung.hibernate.pojo.inheritance.Car; -import com.baeldung.hibernate.pojo.inheritance.MyEmployee; -import com.baeldung.hibernate.pojo.inheritance.Pen; -import com.baeldung.hibernate.pojo.inheritance.Pet; - -public class InheritanceMappingIntegrationTest { - private Session session; - - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory() - .openSession(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenSubclasses_whenQuerySingleTableSuperclass_thenOk() { - Book book = new Book(1, "1984", "George Orwell"); - session.save(book); - Pen pen = new Pen(2, "my pen", "blue"); - session.save(pen); - - assertThat(session.createQuery("from MyProduct") - .getResultList() - .size()).isEqualTo(2); - } - - @Test - public void givenSubclasses_whenQueryMappedSuperclass_thenOk() { - MyEmployee emp = new MyEmployee(1, "john", "baeldung"); - session.save(emp); - - assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Person") - .getResultList() - .size()).isEqualTo(1); - } - - @Test - public void givenSubclasses_whenQueryJoinedTableSuperclass_thenOk() { - Pet pet = new Pet(1, "dog", "lassie"); - session.save(pet); - - assertThat(session.createQuery("from Animal") - .getResultList() - .size()).isEqualTo(1); - } - - @Test - public void givenSubclasses_whenQueryTablePerClassSuperclass_thenOk() { - Car car = new Car(1, "audi", "xyz"); - session.save(car); - - assertThat(session.createQuery("from Vehicle") - .getResultList() - .size()).isEqualTo(1); - } - - @Test - public void givenSubclasses_whenQueryNonMappedInterface_thenOk() { - Bag bag = new Bag(1, "large"); - session.save(bag); - - assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item") - .getResultList() - .size()).isEqualTo(0); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java deleted file mode 100644 index cb73fe348c..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.baeldung.hibernate; - -import com.baeldung.hibernate.entities.Department; -import com.baeldung.hibernate.entities.DeptEmployee; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.junit.*; - -import java.io.IOException; - -public class NamedQueryIntegrationTest { - private static Session session; - - private Transaction transaction; - - private Long purchaseDeptId; - - @BeforeClass - public static void setUpClass() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession(); - } - - @Before - public void setUp() throws IOException { - transaction = session.beginTransaction(); - session.createNativeQuery("delete from deptemployee").executeUpdate(); - session.createNativeQuery("delete from department").executeUpdate(); - Department salesDepartment = new Department("Sales"); - Department purchaseDepartment = new Department("Purchase"); - DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment); - DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment); - DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment); - session.persist(salesDepartment); - session.persist(purchaseDepartment); - purchaseDeptId = purchaseDepartment.getId(); - session.persist(employee1); - session.persist(employee2); - session.persist(employee3); - transaction.commit(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - if(transaction.isActive()) { - transaction.rollback(); - } - } - - @Test - public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() { - Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class); - query.setParameter("employeeNo", "001"); - DeptEmployee result = query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("John Wayne", result.getName()); - } - - @Test - public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() { - Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class); - query.setParameter("name", "John Wayne"); - DeptEmployee result = query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("001", result.getEmployeeNumber()); - } - - @Test - public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() { - @SuppressWarnings("rawtypes") - NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName"); - query.setParameter("name", "John Wayne"); - DeptEmployee result = (DeptEmployee) query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("001", result.getEmployeeNumber()); - } - - @Test - public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() { - Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment"); - spQuery.setParameter("employeeNo", "001"); - Department newDepartment = session.find(Department.class, purchaseDeptId); - spQuery.setParameter("newDepartment", newDepartment); - spQuery.executeUpdate(); - transaction.commit(); - } - - @Test - public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() { - Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation"); - spQuery.setParameter("employeeNumber", "002"); - spQuery.setParameter("newDesignation", "Supervisor"); - spQuery.executeUpdate(); - transaction.commit(); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java deleted file mode 100644 index 91c41af0fe..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.baeldung.hibernate; - -import com.baeldung.hibernate.pojo.TemporalValues; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.time.*; -import java.util.Calendar; -import java.util.TimeZone; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TemporalValuesUnitTest { - - private Session session; - - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory().withOptions() - .jdbcTimeZone(TimeZone.getTimeZone("UTC")) - .openSession(); - transaction = session.beginTransaction(); - session.createNativeQuery("delete from temporalvalues").executeUpdate(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() { - TemporalValues temporalValues = new TemporalValues(); - temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15")); - temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14")); - temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15")); - assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14")); - assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); - - } - - @Test - public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception { - TemporalValues temporalValues = new TemporalValues(); - temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); - temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); - temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332")); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); - assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); - assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); - - } - - @Test - public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception { - TemporalValues temporalValues = new TemporalValues(); - - Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - calendarDate.set(Calendar.YEAR, 2017); - calendarDate.set(Calendar.MONTH, 10); - calendarDate.set(Calendar.DAY_OF_MONTH, 15); - temporalValues.setCalendarDate(calendarDate); - - Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); - temporalValues.setCalendarTimestamp(calendarTimestamp); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); - assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); - - } - - @Test - public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() { - TemporalValues temporalValues = new TemporalValues(); - - temporalValues.setLocalDate(LocalDate.parse("2017-11-15")); - temporalValues.setLocalTime(LocalTime.parse("15:30:18")); - temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00")); - - System.out.println("********"+OffsetTime.parse("08:22:12+01:00").toString()); - temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z")); - temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12")); - temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); - temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15")); - assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18")); - //assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00")); - assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z")); - assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12")); - //assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); - assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); - - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java deleted file mode 100644 index 0b2bdf7ead..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.hibernate.aggregatefunctions; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; - -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.pojo.Student; - -public class AggregateFunctionsIntegrationTest { - - private static Session session; - private static Transaction transaction; - - @BeforeClass - public static final void setup() throws HibernateException, IOException { - session = HibernateUtil.getSessionFactory() - .openSession(); - transaction = session.beginTransaction(); - - Student jonas = new Student("Jonas", 22); - session.save(jonas); - - Student sally = new Student("Sally", 20); - session.save(sally); - - Student simon = new Student("Simon", 25); - session.save(simon); - - Student raven = new Student("Raven", 21); - session.save(raven); - - Student sam = new Student("Sam", 23); - session.save(sam); - - } - - @AfterClass - public static final void teardown() { - if (session != null) { - transaction.rollback(); - session.close(); - } - } - - @Test - public void whenMaxAge_ThenReturnValue() { - int maxAge = (int) session.createQuery("SELECT MAX(age) from Student") - .getSingleResult(); - assertThat(maxAge).isEqualTo(25); - } - - @Test - public void whenMinAge_ThenReturnValue() { - int minAge = (int) session.createQuery("SELECT MIN(age) from Student") - .getSingleResult(); - assertThat(minAge).isEqualTo(20); - } - - @Test - public void whenAverageAge_ThenReturnValue() { - Double avgAge = (Double) session.createQuery("SELECT AVG(age) from Student") - .getSingleResult(); - assertThat(avgAge).isEqualTo(22.2); - } - - @Test - public void whenCountAll_ThenReturnValue() { - Long totalStudents = (Long) session.createQuery("SELECT COUNT(*) from Student") - .getSingleResult(); - assertThat(totalStudents).isEqualTo(5); - } - - @Test - public void whenSumOfAllAges_ThenReturnValue() { - Long sumOfAllAges = (Long) session.createQuery("SELECT SUM(age) from Student") - .getSingleResult(); - assertThat(sumOfAllAges).isEqualTo(111); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java deleted file mode 100644 index 3cd4761a7b..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.baeldung.hibernate.converter; - -import java.io.IOException; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.pojo.Person; -import com.baeldung.hibernate.pojo.PersonName; - -import static org.junit.Assert.assertEquals; - -public class PersonNameConverterUnitTest { - - private Session session; - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory() - .openSession(); - transaction = session.beginTransaction(); - - session.createNativeQuery("delete from personTable") - .executeUpdate(); - - transaction.commit(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenPersonName_WhenSaving_ThenNameAndSurnameConcat() { - final String name = "name"; - final String surname = "surname"; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals(surname + ", " + name, dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName() - .getName(), name); - assertEquals(dbPerson.getPersonName() - .getSurname(), surname); - } - - @Test - public void givenPersonNameNull_WhenSaving_ThenNullStored() { - final String name = null; - final String surname = null; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName(), null); - } - - @Test - public void givenPersonNameWithoutName_WhenSaving_ThenNotNameStored() { - final String name = null; - final String surname = "surname"; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("surname, ", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName() - .getName(), name); - assertEquals(dbPerson.getPersonName() - .getSurname(), surname); - } - - @Test - public void givenPersonNameWithoutSurName_WhenSaving_ThenNotSurNameStored() { - final String name = "name"; - final String surname = null; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("name", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName() - .getName(), name); - assertEquals(dbPerson.getPersonName() - .getSurname(), surname); - } - - @Test - public void givenPersonNameEmptyFields_WhenSaving_ThenFielsNotStored() { - final String name = ""; - final String surname = ""; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName(), null); - } - -} 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 deleted file mode 100644 index cedba412d9..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java +++ /dev/null @@ -1,89 +0,0 @@ -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("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/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java deleted file mode 100644 index 63dc6330be..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.hibernate.customtypes; - -import com.baeldung.hibernate.HibernateUtil; -import org.hibernate.SessionFactory; -import org.hibernate.query.Query; -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; -import java.time.LocalDate; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; - -public class HibernateCustomTypesManualTest { - - @Test - public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() throws IOException { - - final OfficeEmployee e = new OfficeEmployee(); - e.setDateOfJoining(LocalDate.now()); - - PhoneNumber number = new PhoneNumber(1, 222, 8781902); - e.setEmployeeNumber(number); - - Address empAdd = new Address(); - empAdd.setAddressLine1("Street"); - empAdd.setAddressLine2("Area"); - empAdd.setCity("City"); - empAdd.setCountry("Country"); - empAdd.setZipCode(100); - - e.setEmpAddress(empAdd); - - Salary empSalary = new Salary(); - empSalary.setAmount(1000L); - empSalary.setCurrency("USD"); - e.setSalary(empSalary); - - doInHibernate(this::sessionFactory, session -> { - session.save(e); - boolean contains = session.contains(e); - Assert.assertTrue(contains); - }); - - } - - @Test - public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() throws IOException { - - final OfficeEmployee e = new OfficeEmployee(); - e.setDateOfJoining(LocalDate.now()); - - PhoneNumber number = new PhoneNumber(1, 222, 8781902); - e.setEmployeeNumber(number); - - Address empAdd = new Address(); - empAdd.setAddressLine1("Street"); - empAdd.setAddressLine2("Area"); - empAdd.setCity("City"); - empAdd.setCountry("Country"); - empAdd.setZipCode(100); - e.setEmpAddress(empAdd); - - Salary empSalary = new Salary(); - empSalary.setAmount(1000L); - empSalary.setCurrency("USD"); - e.setSalary(empSalary); - - doInHibernate(this::sessionFactory, session -> { - session.save(e); - - Query query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode"); - query.setParameter("pinCode",100); - int size = query.list().size(); - - Assert.assertEquals(1, size); - }); - - } - - private SessionFactory sessionFactory() { - try { - return HibernateUtil.getSessionFactory("hibernate-customtypes.properties"); - } catch (IOException e) { - e.printStackTrace(); - } - - return null; - } -} 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 deleted file mode 100644 index 3581c81daa..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java +++ /dev/null @@ -1,425 +0,0 @@ -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/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java deleted file mode 100644 index 8a1b9e9791..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.hibernate.findall; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.pojo.Student; - -public class FindAllUnitTest { - - private Session session; - private Transaction transaction; - - private FindAll findAll; - - @Before - public void setUp() throws IOException { - - session = HibernateUtil.getSessionFactory().openSession(); - transaction = session.beginTransaction(); - findAll = new FindAll(session); - - session.createNativeQuery("delete from Student").executeUpdate(); - - Student student1 = new Student(); - session.persist(student1); - - Student student2 = new Student(); - session.persist(student2); - - Student student3 = new Student(); - session.persist(student3); - - transaction.commit(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenCriteriaQuery_WhenFindAll_ThenGetAllPersons() { - List list = findAll.findAllWithCriteriaQuery(); - assertEquals(3, list.size()); - } - - @Test - public void givenJpql_WhenFindAll_ThenGetAllPersons() { - List list = findAll.findAllWithJpql(); - assertEquals(3, list.size()); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java deleted file mode 100644 index 0998ff1d90..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.hibernate.joincolumn; - -import com.baeldung.hibernate.HibernateUtil; -import java.io.IOException; -import org.hibernate.Session; -import org.hibernate.Transaction; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - - -public class JoinColumnIntegrationTest { - - private Session session; - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") - .openSession(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenOfficeEntity_setAddress_shouldPersist() { - Office office = new Office(); - - OfficeAddress address = new OfficeAddress(); - address.setZipCode("11-111"); - office.setAddress(address); - - session.save(office); - session.flush(); - session.clear(); - } - - @Test - public void givenEmployeeEntity_setEmails_shouldPersist() { - OfficialEmployee employee = new OfficialEmployee(); - - Email email = new Email(); - email.setAddress("example@email.com"); - email.setEmployee(employee); - - session.save(employee); - session.flush(); - session.clear(); - } - -} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java deleted file mode 100644 index 2b12734a10..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.baeldung.hibernate.jpacriteriabuilder; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import javax.persistence.EntityManager; - -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.entities.Department; -import com.baeldung.hibernate.entities.DeptEmployee; -import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchService; -import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchServiceImpl; - -public class EmployeeSearchServiceIntegrationTest { - - private EntityManager entityManager; - private EmployeeSearchService searchService; - private Session session; - - @Before - public final void setup() throws HibernateException, IOException { - session = HibernateUtil.getSessionFactory() - .openSession(); - entityManager = session.getEntityManagerFactory() - .createEntityManager(); - searchService = new EmployeeSearchServiceImpl(entityManager); - - entityManager.getTransaction() - .begin(); - Department department = new Department("Pre Sales"); - DeptEmployee employee = new DeptEmployee("John Smith", "001", "Manager", department); - entityManager.persist(department); - entityManager.persist(employee); - employee = new DeptEmployee("Ian Evans", "002", "Associate", department); - entityManager.persist(department); - entityManager.persist(employee); - department = new Department("Copporate Sales"); - employee = new DeptEmployee("Robert Carter", "003", "Manager", department); - entityManager.persist(department); - entityManager.persist(employee); - employee = new DeptEmployee("John Carter", "004", "Senior Manager", department); - entityManager.persist(employee); - employee = new DeptEmployee("David Guetta", "009", "Associate", department); - entityManager.persist(department); - entityManager.persist(employee); - department = new Department("Post Sales"); - employee = new DeptEmployee("Robert Jonas", "005", "Director", department); - entityManager.persist(department); - entityManager.persist(employee); - employee = new DeptEmployee("John Ferros", "006", "Junior Associate", department); - entityManager.persist(department); - entityManager.persist(employee); - department = new Department("Client Support"); - employee = new DeptEmployee("Robert Mcclements", "007", "Director", department); - entityManager.persist(department); - entityManager.persist(employee); - employee = new DeptEmployee("Peter Parker", "008", "Manager", department); - entityManager.persist(department); - entityManager.persist(employee); - - } - - @After - public final void teardown() { - entityManager.getTransaction() - .rollback(); - entityManager.close(); - } - - @Test - public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() { - List titles = new ArrayList() { - { - add("Manager"); - add("Senior Manager"); - add("Director"); - } - }; - List result = searchService.filterbyTitleUsingCriteriaBuilder(titles); - assertEquals("Number of Employees does not match with expected.", 6, result.size()); - assertThat(result.stream() - .map(DeptEmployee::getTitle) - .distinct() - .collect(Collectors.toList()), containsInAnyOrder(titles.toArray())); - } - - @Test - public final void givenCriteriaQuery_whenSearchedUsingExpressionWithListofAuthors_thenResultIsFilteredByAuthorNames() { - List titles = new ArrayList() { - { - add("Manager"); - add("Senior Manager"); - add("Director"); - } - }; - List result = searchService.filterbyTitleUsingExpression(titles); - assertEquals("Number of Employees does not match with expected.", 6, result.size()); - assertThat(result.stream() - .map(DeptEmployee::getTitle) - .distinct() - .collect(Collectors.toList()), containsInAnyOrder(titles.toArray())); - } - - @Test - public final void givenCriteriaQuery_whenSearchedDepartmentLike_thenResultIsFilteredByDepartment() { - List result = searchService.searchByDepartmentQuery("Sales"); - assertEquals("Number of Employees does not match with expected.", 7, result.size()); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java deleted file mode 100644 index 398b2290fa..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.hibernate.lob; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; - -import org.apache.commons.io.IOUtils; -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.lob.model.User; - -public class LobUnitTest { - - private Session session; - - @Before - public void init(){ - try { - session = HibernateSessionUtil.getSessionFactory("hibernate.properties") - .openSession(); - } catch (HibernateException | IOException e) { - fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); - } - } - - @After - public void close(){ - if(session != null) session.close(); - } - - @Test - public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){ - User user = new User(); - try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) { - // Get Image file from the resource - if(inputStream == null) fail("Unable to get resources"); - user.setId("1"); - user.setName("User"); - user.setPhoto(IOUtils.toByteArray(inputStream)); - - session.persist(user); - } catch (IOException e) { - fail("Unable to read input stream"); - } - - User result = session.find(User.class, "1"); - - assertNotNull("Query result is null", result); - assertEquals("User's name is invalid", user.getName(), result.getName() ); - assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) ); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java deleted file mode 100644 index 1b6cee7e67..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.hibernate.multitenancy; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity(name = "Car") -@Table(name = "Car") -public class Car implements Serializable { - - private static final long serialVersionUID = 1015320564683423342L; - - private String brand; - - @Id - public String getBrand() { - return brand; - } - - public void setBrand(String brand) { - this.brand = brand; - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java deleted file mode 100644 index fdc3f9fa81..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.baeldung.hibernate.multitenancy; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.io.IOException; -import java.util.Properties; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.context.spi.CurrentTenantIdentifierResolver; -import org.hibernate.service.ServiceRegistry; -import org.junit.Before; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import com.baeldung.hibernate.multitenancy.database.TenantIdNames; - -public abstract class MultitenancyIntegrationTest { - - public abstract String getPropertyFile(); - - @Mock - private CurrentTenantIdentifierResolver currentTenantIdentifierResolver; - - private SessionFactory sessionFactory; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - - Mockito.when(currentTenantIdentifierResolver.validateExistingCurrentSessions()) - .thenReturn(false); - - Properties properties = getHibernateProperties(); - properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver); - - sessionFactory = buildSessionFactory(properties); - - initTenant(TenantIdNames.MYDB1); - initTenant(TenantIdNames.MYDB2); - } - - protected void initTenant(String tenantId) { - whenCurrentTenantIs(tenantId); - createCarTable(); - } - - protected void whenCurrentTenantIs(String tenantId) { - Mockito.when(currentTenantIdentifierResolver.resolveCurrentTenantIdentifier()) - .thenReturn(tenantId); - } - - protected void whenAddCar(String brand) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - Car car = new Car(); - car.setBrand(brand); - session.save(car); - tx.commit(); - } - - protected void thenCarFound(String brand) { - Session session = sessionFactory.openSession(); - assertNotNull(session.get(Car.class, brand)); - } - - protected void thenCarNotFound(String brand) { - Session session = sessionFactory.openSession(); - assertNull(session.get(Car.class, brand)); - } - - @SuppressWarnings("deprecation") - private void createCarTable() { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - session.createSQLQuery("drop table Car if exists") - .executeUpdate(); - session.createSQLQuery("create table Car (brand varchar(255) primary key)") - .executeUpdate(); - tx.commit(); - } - - private Properties getHibernateProperties() throws IOException { - Properties properties = new Properties(); - properties.load(getClass().getResourceAsStream(getPropertyFile())); - return properties; - } - - private static SessionFactory buildSessionFactory(Properties properties) { - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties) - .build(); - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - metadataSources.addAnnotatedClass(Car.class); - return metadataSources.buildMetadata() - .buildSessionFactory(); - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java deleted file mode 100644 index 92f477a646..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.hibernate.multitenancy.database; - -import java.io.IOException; - -import org.junit.Test; - -import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; - -public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyIntegrationTest { - - @Override - public String getPropertyFile() { - return "/hibernate-database-multitenancy.properties"; - } - - @Test - public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException { - whenCurrentTenantIs(TenantIdNames.MYDB1); - whenAddCar("myCar"); - thenCarFound("myCar"); - whenCurrentTenantIs(TenantIdNames.MYDB2); - thenCarNotFound("myCar"); - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java deleted file mode 100644 index eb1f410622..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.hibernate.multitenancy.database; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; -import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; -import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; - -@SuppressWarnings("serial") -public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { - - private final Map connectionProviderMap = new HashMap<>(); - - public MapMultiTenantConnectionProvider() throws IOException { - initConnectionProviderForTenant(TenantIdNames.MYDB1); - initConnectionProviderForTenant(TenantIdNames.MYDB2); - } - - @Override - protected ConnectionProvider getAnyConnectionProvider() { - return connectionProviderMap.values() - .iterator() - .next(); - } - - @Override - protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { - return connectionProviderMap.get(tenantIdentifier); - } - - private void initConnectionProviderForTenant(String tenantId) throws IOException { - Properties properties = new Properties(); - properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId))); - DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); - connectionProvider.configure(properties); - this.connectionProviderMap.put(tenantId, connectionProvider); - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java deleted file mode 100644 index 231272fa63..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.hibernate.multitenancy.database; - -public class TenantIdNames { - public static final String MYDB1 = "mydb1"; - public static final String MYDB2 = "mydb2"; -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java deleted file mode 100644 index 304af65fca..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.hibernate.multitenancy.schema; - -import java.io.IOException; - -import org.junit.Test; - -import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; -import com.baeldung.hibernate.multitenancy.database.TenantIdNames; - -public class SchemaApproachMultitenancyIntegrationTest extends MultitenancyIntegrationTest { - - @Override - public String getPropertyFile() { - return "/hibernate-schema-multitenancy.properties"; - } - - @Test - public void givenSchemaApproach_whenAddingEntries_thenOnlyAddedToConcreteSchema() throws IOException { - whenCurrentTenantIs(TenantIdNames.MYDB1); - whenAddCar("Ferrari"); - thenCarFound("Ferrari"); - whenCurrentTenantIs(TenantIdNames.MYDB2); - thenCarNotFound("Ferrari"); - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java deleted file mode 100644 index 601eba651c..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.hibernate.multitenancy.schema; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Properties; - -import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; -import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; -import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; - -@SuppressWarnings("serial") -public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { - - private final ConnectionProvider connectionProvider; - - public SchemaMultiTenantConnectionProvider() throws IOException { - connectionProvider = initConnectionProvider(); - } - - @Override - protected ConnectionProvider getAnyConnectionProvider() { - return connectionProvider; - } - - @Override - protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { - return connectionProvider; - } - - @Override - public Connection getConnection(String tenantIdentifier) throws SQLException { - Connection connection = super.getConnection(tenantIdentifier); - connection.createStatement() - .execute(String.format("SET SCHEMA %s;", tenantIdentifier)); - return connection; - } - - private ConnectionProvider initConnectionProvider() throws IOException { - Properties properties = new Properties(); - properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties")); - - DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); - connectionProvider.configure(properties); - return connectionProvider; - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java deleted file mode 100644 index 2eba94e307..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.hibernate.multitenancy.schema; - -public class TenantIdNames { - public static final String MYDB1 = "mydb1"; - public static final String MYDB2 = "mydb2"; -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java deleted file mode 100644 index 475c93f6ff..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.baeldung.hibernate.onetoone; - -import com.baeldung.hibernate.onetoone.foreignkeybased.Address; -import com.baeldung.hibernate.onetoone.foreignkeybased.User; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class HibernateOneToOneAnnotationFKBasedIntegrationTest { - - private static SessionFactory sessionFactory; - - private Session session; - - @BeforeClass - public static void beforeTests() { - sessionFactory = HibernateUtil.getSessionFactory(Strategy.FOREIGN_KEY); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - } - - @Test - public void givenData_whenInsert_thenCreates1to1relationship() { - User user = new User(); - user.setUserName("alice@baeldung.com"); - - Address address = new Address(); - address.setStreet("FK Street"); - address.setCity("FK City"); - - address.setUser(user); - user.setAddress(address); - - //Address entry will automatically be created by hibernate, since cascade type is specified as ALL - session.persist(user); - session.getTransaction().commit(); - - assert1to1InsertedData(); - } - - private void assert1to1InsertedData() { - @SuppressWarnings("unchecked") - List userList = session.createQuery("FROM User").list(); - - assertNotNull(userList); - assertEquals(1, userList.size()); - - User user = userList.get(0); - assertEquals("alice@baeldung.com", user.getUserName()); - - Address address = user.getAddress(); - assertNotNull(address); - assertEquals("FK Street", address.getStreet()); - assertEquals("FK City", address.getCity()); - - } - - @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/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java deleted file mode 100644 index df4cd4d137..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.baeldung.hibernate.onetoone; - -import com.baeldung.hibernate.onetoone.jointablebased.Employee; -import com.baeldung.hibernate.onetoone.jointablebased.WorkStation; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class HibernateOneToOneAnnotationJTBasedIntegrationTest { - - private static SessionFactory sessionFactory; - - private Session session; - - @BeforeClass - public static void beforeTests() { - sessionFactory = HibernateUtil.getSessionFactory(Strategy.JOIN_TABLE_BASED); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - } - - @Test - public void givenData_whenInsert_thenCreates1to1relationship() { - Employee employee = new Employee(); - employee.setName("bob@baeldung.com"); - - WorkStation workStation = new WorkStation(); - workStation.setWorkstationNumber(626); - workStation.setFloor("Sixth Floor"); - - - employee.setWorkStation(workStation); - workStation.setEmployee(employee); - - session.persist(employee); - session.getTransaction().commit(); - - assert1to1InsertedData(); - } - - private void assert1to1InsertedData() { - @SuppressWarnings("unchecked") - List employeeList = session.createQuery("FROM Employee").list(); - assertNotNull(employeeList); - assertEquals(1, employeeList.size()); - - Employee employee = employeeList.get(0); - assertEquals("bob@baeldung.com", employee.getName()); - - WorkStation workStation = employee.getWorkStation(); - - assertNotNull(workStation); - assertEquals((long) 626, (long) workStation.getWorkstationNumber()); - assertEquals("Sixth Floor", workStation.getFloor()); - - } - - @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/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java deleted file mode 100644 index 7931a8e3fe..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.hibernate.onetoone; - -import com.baeldung.hibernate.onetoone.sharedkeybased.Address; -import com.baeldung.hibernate.onetoone.sharedkeybased.User; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class HibernateOneToOneAnnotationSPKBasedIntegrationTest { - - private static SessionFactory sessionFactory; - - private Session session; - - @BeforeClass - public static void beforeTests() { - sessionFactory = HibernateUtil.getSessionFactory(Strategy.SHARED_PRIMARY_KEY); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - } - - @Test - public void givenData_whenInsert_thenCreates1to1relationship() { - User user = new User(); - user.setUserName("alice@baeldung.com"); - - Address address = new Address(); - address.setStreet("SPK Street"); - address.setCity("SPK City"); - - address.setUser(user); - user.setAddress(address); - - //Address entry will automatically be created by hibernate, since cascade type is specified as ALL - session.persist(user); - session.getTransaction().commit(); - - assert1to1InsertedData(); - } - - - private void assert1to1InsertedData() { - @SuppressWarnings("unchecked") - List userList = session.createQuery("FROM User").list(); - assertNotNull(userList); - assertEquals(1, userList.size()); - - User user = userList.get(0); - assertEquals("alice@baeldung.com", user.getUserName()); - - Address address = user.getAddress(); - assertNotNull(address); - assertEquals("SPK Street", address.getStreet()); - assertEquals("SPK City", address.getCity()); - } - - @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/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java deleted file mode 100644 index 37c490f297..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.baeldung.hibernate.optimisticlocking; - -import java.io.IOException; -import java.util.Arrays; - -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import javax.persistence.OptimisticLockException; - -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.HibernateUtil; - -public class OptimisticLockingIntegrationTest { - - private static SessionFactory sessionFactory; - - @Before - public void setUp() throws IOException { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH"); - OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course)); - course.setStudent(student); - entityManager.persist(course); - entityManager.persist(student); - entityManager.getTransaction() - .commit(); - entityManager.close(); - } - - @After - public void clean() throws IOException { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L); - OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L); - entityManager.remove(course); - entityManager.remove(student); - entityManager.getTransaction() - .commit(); - entityManager.close(); - } - - @Test(expected = OptimisticLockException.class) - public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { - EntityManager em = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); - - EntityManager em2 = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); - student2.setName("RICHARD"); - em2.persist(student2); - em2.getTransaction() - .commit(); - em2.close(); - - student.setName("JOHN"); - em.persist(student); - em.getTransaction() - .commit(); - em.close(); - } - - @Test(expected = OptimisticLockException.class) - public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { - EntityManager em = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC); - - EntityManager em2 = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); - student2.setName("RICHARD"); - em2.persist(student2); - em2.getTransaction() - .commit(); - em2.close(); - - student.setName("JOHN"); - em.persist(student); - em.getTransaction() - .commit(); - em.close(); - } - - @Test(expected = OptimisticLockException.class) - public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { - EntityManager em = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); - em.refresh(student, LockModeType.OPTIMISTIC); - - EntityManager em2 = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); - em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); - student2.setName("RICHARD"); - em2.persist(student2); - em2.getTransaction() - .commit(); - em2.close(); - - student.setName("JOHN"); - em.persist(student); - em.getTransaction() - .commit(); - em.close(); - } - - @Test(expected = OptimisticLockException.class) - public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { - EntityManager em = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); - em.lock(student, LockModeType.OPTIMISTIC); - - EntityManager em2 = getEntityManagerWithOpenTransaction(); - OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); - em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); - student2.setName("RICHARD"); - em2.persist(student2); - em2.getTransaction() - .commit(); - em2.close(); - - student.setName("JOHN"); - em.persist(student); - em.getTransaction() - .commit(); - em.close(); - } - - protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { - String propertyFileName = "hibernate-pessimistic-locking.properties"; - if (sessionFactory == null) { - sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); - } - EntityManager entityManager = sessionFactory.openSession(); - entityManager.getTransaction().begin(); - - return entityManager; - } - - @AfterClass - public static void afterTests() { - sessionFactory.close(); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java deleted file mode 100644 index 4b9c7720fd..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import com.baeldung.hibernate.HibernateUtil; -import com.vividsolutions.jts.util.Assert; - -import org.hibernate.SessionFactory; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.persistence.*; -import java.io.IOException; -import java.util.Arrays; - -public class BasicPessimisticLockingIntegrationTest { - - private static SessionFactory sessionFactory; - - @BeforeClass - public static void setUp() throws IOException { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOHN"); - PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "MATH", student); - student.setCourses(Arrays.asList(course)); - entityManager.persist(course); - entityManager.persist(student); - entityManager.getTransaction() - .commit(); - entityManager.close(); - } - - @Test - public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLockExceptionThrown() { - try { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - entityManager.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ); - - EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); - entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ); - - entityManager.close(); - entityManager2.close(); - } catch (Exception e) { - Assert.isTrue(e instanceof PessimisticLockException); - } - } - - @Test - public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException { - try { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - Query query = entityManager.createQuery("from Student where studentId = :studentId"); - query.setParameter("studentId", 1L); - query.setLockMode(LockModeType.PESSIMISTIC_WRITE); - query.getResultList(); - - EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); - Query query2 = entityManager2.createQuery("from Student where studentId = :studentId"); - query2.setParameter("studentId", 1L); - query2.setLockMode(LockModeType.PESSIMISTIC_READ); - query2.getResultList(); - - entityManager.close(); - entityManager2.close(); - } catch (Exception e) { - Assert.isTrue(e instanceof PessimisticLockException); - } - } - - @Test - public void givenRecordWithPessimisticReadLock_whenFindingNewOne_PessimisticLockExceptionThrown() { - try { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); - entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_READ); - - EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); - entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_FORCE_INCREMENT); - - entityManager.close(); - entityManager2.close(); - } catch (Exception e) { - Assert.isTrue(e instanceof PessimisticLockException); - } - } - - @Test - public void givenRecordAndRefreshWithPessimisticRead_whenFindingWithPessimisticWrite_PessimisticLockExceptionThrown() { - try { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); - entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT); - - EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); - entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_WRITE); - - entityManager.close(); - entityManager2.close(); - } catch (Exception e) { - Assert.isTrue(e instanceof PessimisticLockException); - } - } - - @Test - public void givenRecordWithPessimisticRead_whenUpdatingRecord_PessimisticLockExceptionThrown() { - try { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); - entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_READ); - - EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L); - resultStudent2.setName("Change"); - entityManager2.persist(resultStudent2); - entityManager2.getTransaction() - .commit(); - - entityManager.close(); - entityManager2.close(); - } catch (Exception e) { - Assert.isTrue(e instanceof PessimisticLockException); - } - } - - @Test - public void givenRecordWithPessimisticWrite_whenUpdatingRecord_PessimisticLockExceptionThrown() { - try { - EntityManager entityManager = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); - entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_WRITE); - - EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L); - resultStudent2.setName("Change"); - entityManager2.persist(resultStudent2); - entityManager2.getTransaction() - .commit(); - - entityManager.close(); - entityManager2.close(); - } catch (Exception e) { - Assert.isTrue(e instanceof PessimisticLockException); - } - } - - protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { - String propertyFileName = "hibernate-pessimistic-locking.properties"; - if (sessionFactory == null) { - sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); - } - EntityManager entityManager = sessionFactory.openSession(); - entityManager.getTransaction().begin(); - - return entityManager; - } - - @AfterClass - public static void afterTests() { - sessionFactory.close(); - } - -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java deleted file mode 100644 index 81cb7d95f8..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.baeldung.hibernate.pessimisticlocking; - -import com.baeldung.hibernate.HibernateUtil; - -import org.hibernate.SessionFactory; -import org.junit.AfterClass; -import org.junit.Test; - -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import javax.persistence.PessimisticLockScope; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class PessimisticLockScopesIntegrationTest { - - private static SessionFactory sessionFactory; - - @Test - public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException { - EntityManager em = getEntityManagerWithOpenTransaction(); - PessimisticLockingEmployee employee = new PessimisticLockingEmployee(1L, "JOHN", "SMITH", new BigDecimal(4.5)); - em.persist(employee); - em.getTransaction() - .commit(); - em.close(); - - // NORMAL SCOPE - EntityManager em2 = getEntityManagerWithOpenTransaction(); - PessimisticLockingEmployee foundEmployee = em2.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE); - em2.getTransaction() - .rollback(); - - // EXTENDED SCOPE - Map map = new HashMap<>(); - map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); - - EntityManager em3 = getEntityManagerWithOpenTransaction(); - foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); - em3.getTransaction() - .rollback(); - - em2.close(); - em3.close(); - } - - @Test - public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException { - EntityManager em = getEntityManagerWithOpenTransaction(); - Address address = new Address("Poland", "Warsaw"); - Customer customer = new Customer(1L, "JOE", "DOE", Arrays.asList(address)); - em.persist(customer); - em.getTransaction() - .commit(); - em.close(); - - // NORMAL SCOPE - EntityManager em2 = getEntityManagerWithOpenTransaction(); - Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE); - em2.getTransaction() - .rollback(); - - // EXTENDED SCOPE - Map map = new HashMap<>(); - map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); - - EntityManager em3 = getEntityManagerWithOpenTransaction(); - foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); - em2.getTransaction() - .rollback(); - - em2.close(); - em3.close(); - } - - @Test - public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException { - EntityManager em = getEntityManagerWithOpenTransaction(); - PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOE"); - PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "COURSE", student); - student.setCourses(Arrays.asList(course)); - em.persist(course); - em.persist(student); - em.getTransaction() - .commit(); - em.close(); - - // NORMAL SCOPE - EntityManager em2 = getEntityManagerWithOpenTransaction(); - PessimisticLockingCourse foundCourse = em2.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE); - em2.getTransaction() - .rollback(); - - // EXTENDED SCOPE - Map map = new HashMap<>(); - map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); - - EntityManager em3 = getEntityManagerWithOpenTransaction(); - foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); - em3.getTransaction() - .rollback(); - - em2.close(); - em3.close(); - } - - protected EntityManager getEntityManagerWithOpenTransaction() throws IOException { - String propertyFileName = "hibernate-pessimistic-locking.properties"; - if (sessionFactory == null) { - sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); - } - EntityManager entityManager = sessionFactory.openSession(); - entityManager.getTransaction().begin(); - - return entityManager; - } - - @AfterClass - public static void afterTests() { - sessionFactory.close(); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java deleted file mode 100644 index 13eae3d877..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.baeldung.hibernate.queryplancache; - -import com.baeldung.hibernate.HibernateUtil; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.jpa.QueryHints; -import org.hibernate.query.Query; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Param; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.TearDown; -import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.infra.Blackhole; -import org.openjdk.jmh.runner.RunnerException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -public class QueryPlanCacheBenchmark { - - private static final Logger LOGGER = LoggerFactory.getLogger(QueryPlanCacheBenchmark.class); - - @State(Scope.Thread) - public static class QueryPlanCacheBenchMarkState { - @Param({"1", "2", "3"}) - public int planCacheSize; - - public Session session; - - @Setup - public void stateSetup() throws IOException { - LOGGER.info("State - Setup"); - session = initSession(planCacheSize); - LOGGER.info("State - Setup Complete"); - } - - private Session initSession(int planCacheSize) throws IOException { - Properties properties = HibernateUtil.getProperties(); - properties.put("hibernate.query.plan_cache_max_size", planCacheSize); - properties.put("hibernate.query.plan_parameter_metadata_max_size", planCacheSize); - SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties); - return sessionFactory.openSession(); - } - - @TearDown - public void tearDownState() { - LOGGER.info("State - Teardown"); - SessionFactory sessionFactory = session.getSessionFactory(); - session.close(); - sessionFactory.close(); - LOGGER.info("State - Teardown complete"); - } - } - - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MICROSECONDS) - @Fork(1) - @Warmup(iterations = 2) - @Measurement(iterations = 5) - public void givenQueryPlanCacheSize_thenCompileQueries(QueryPlanCacheBenchMarkState state, Blackhole blackhole) { - - Query query1 = findEmployeesByDepartmentNameQuery(state.session); - Query query2 = findEmployeesByDesignationQuery(state.session); - Query query3 = findDepartmentOfAnEmployeeQuery(state.session); - - blackhole.consume(query1); - blackhole.consume(query2); - blackhole.consume(query3); - - } - - private Query findEmployeesByDepartmentNameQuery(Session session) { - return session.createQuery("SELECT e FROM DeptEmployee e " + - "JOIN e.department WHERE e.department.name = :deptName") - .setMaxResults(30) - .setHint(QueryHints.HINT_FETCH_SIZE, 30); - } - - private Query findEmployeesByDesignationQuery(Session session) { - return session.createQuery("SELECT e FROM DeptEmployee e " + - "WHERE e.title = :designation") - .setHint(QueryHints.SPEC_HINT_TIMEOUT, 1000); - } - - private Query findDepartmentOfAnEmployeeQuery(Session session) { - return session.createQuery("SELECT e.department FROM DeptEmployee e " + - "JOIN e.department WHERE e.employeeNumber = :empId"); - - } - - public static void main(String... args) throws IOException, RunnerException { - //main-class to run the benchmark - org.openjdk.jmh.Main.main(args); - } -} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java deleted file mode 100644 index 246a7d59f9..0000000000 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.hibernate.transaction; - -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.pojo.Post; -import com.baeldung.hibernate.transaction.PostService; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -public class TransactionIntegrationTest { - - private static PostService postService; - private static Session session; - private static Logger logger = LoggerFactory.getLogger(TransactionIntegrationTest.class); - - @BeforeClass - public static void init() throws IOException { - Properties properties = new Properties(); - properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); - properties.setProperty("hibernate.connection.url", "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); - properties.setProperty("hibernate.connection.username", "sa"); - properties.setProperty("hibernate.show_sql", "true"); - properties.setProperty("jdbc.password", ""); - properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); - properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); - SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties); - session = sessionFactory.openSession(); - postService = new PostService(session); - } - - @Test - public void givenTitleAndBody_whenRepositoryUpdatePost_thenUpdatePost() { - - Post post = new Post("This is a title", "This is a sample post"); - session.persist(post); - - String title = "[UPDATE] Java HowTos"; - String body = "This is an updated posts on Java how-tos"; - postService.updatePost(title, body, post.getId()); - - session.refresh(post); - - assertEquals(post.getTitle(), title); - assertEquals(post.getBody(), body); - } - - -} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties deleted file mode 100644 index c14782ce0f..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties +++ /dev/null @@ -1,14 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;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 diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties deleted file mode 100644 index 853fa80dfc..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties +++ /dev/null @@ -1,2 +0,0 @@ -hibernate.multiTenancy=DATABASE -hibernate.multi_tenant_connection_provider=com.baeldung.hibernate.multitenancy.database.MapMultiTenantConnectionProvider \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties deleted file mode 100644 index 345f1dbbea..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties +++ /dev/null @@ -1,4 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 -hibernate.connection.username=sa -hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties deleted file mode 100644 index 626b7853c6..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties +++ /dev/null @@ -1,4 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb2;DB_CLOSE_DELAY=-1 -hibernate.connection.username=sa -hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties deleted file mode 100644 index e08a23166d..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties +++ /dev/null @@ -1,16 +0,0 @@ -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/hibernate5/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties deleted file mode 100644 index 457f965347..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties +++ /dev/null @@ -1,9 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' -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 \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties deleted file mode 100644 index 4f1ff5e93a..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties +++ /dev/null @@ -1,8 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE -hibernate.connection.username=sa -hibernate.connection.autocommit=true -hibernate.dialect=org.hibernate.dialect.H2Dialect - -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties deleted file mode 100644 index 4abb621355..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties +++ /dev/null @@ -1,7 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS MYDB1\\;CREATE SCHEMA IF NOT EXISTS MYDB2\\; -hibernate.connection.username=sa -hibernate.connection.autocommit=true -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.multiTenancy=SCHEMA -hibernate.multi_tenant_connection_provider=com.baeldung.hibernate.multitenancy.schema.SchemaMultiTenantConnectionProvider \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties deleted file mode 100644 index 1657c838e3..0000000000 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties +++ /dev/null @@ -1,14 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 -hibernate.connection.username=sa -hibernate.connection.autocommit=true -jdbc.password= - -hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect -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 From 592df829e60a68045e6332f2a74f1a0141c52438 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:19:46 +0530 Subject: [PATCH 04/17] JAVA-4 : added new module hibernate-annotations --- .../hibernate5-annotations/README.md | 10 ++ .../hibernate5-annotations/pom.xml | 74 ++++++++ .../com/baeldung/hibernate/HibernateUtil.java | 73 ++++++++ .../UnsupportedTenancyException.java | 8 + .../hibernate/customtypes/Address.java | 69 +++++++ .../hibernate/customtypes/AddressType.java | 169 ++++++++++++++++++ .../LocalDateStringJavaDescriptor.java | 51 ++++++ .../customtypes/LocalDateStringType.java | 34 ++++ .../hibernate/customtypes/OfficeEmployee.java | 88 +++++++++ .../hibernate/customtypes/PhoneNumber.java | 43 +++++ .../customtypes/PhoneNumberType.java | 98 ++++++++++ .../hibernate/customtypes/Salary.java | 39 ++++ .../customtypes/SalaryCurrencyConvertor.java | 15 ++ .../hibernate/customtypes/SalaryType.java | 161 +++++++++++++++++ .../baeldung/hibernate/joincolumn/Email.java | 47 +++++ .../baeldung/hibernate/joincolumn/Office.java | 41 +++++ .../hibernate/joincolumn/OfficeAddress.java | 34 ++++ .../joincolumn/OfficialEmployee.java | 36 ++++ .../com/baeldung/hibernate/pojo/Phone.java | 50 ++++++ .../main/resources/META-INF/persistence.xml | 18 ++ .../src/main/resources/logback.xml | 13 ++ .../HibernateCustomTypesManualTest.java | 90 ++++++++++ .../joincolumn/JoinColumnIntegrationTest.java | 57 ++++++ .../resources/hibernate-spatial.properties | 14 ++ .../src/test/resources/log4j.xml | 25 +++ .../src/test/resources/log4j2.xml | 18 ++ .../src/test/resources/logback.xml | 18 ++ .../src/test/resources/profile.png | Bin 0 -> 1117 bytes 28 files changed, 1393 insertions(+) create mode 100644 persistence-modules/hibernate5-annotations/README.md create mode 100644 persistence-modules/hibernate5-annotations/pom.xml create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/resources/META-INF/persistence.xml create mode 100644 persistence-modules/hibernate5-annotations/src/main/resources/logback.xml create mode 100644 persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java create mode 100644 persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java create mode 100644 persistence-modules/hibernate5-annotations/src/test/resources/hibernate-spatial.properties create mode 100644 persistence-modules/hibernate5-annotations/src/test/resources/log4j.xml create mode 100644 persistence-modules/hibernate5-annotations/src/test/resources/log4j2.xml create mode 100644 persistence-modules/hibernate5-annotations/src/test/resources/logback.xml create mode 100644 persistence-modules/hibernate5-annotations/src/test/resources/profile.png diff --git a/persistence-modules/hibernate5-annotations/README.md b/persistence-modules/hibernate5-annotations/README.md new file mode 100644 index 0000000000..da3c5ad1fd --- /dev/null +++ b/persistence-modules/hibernate5-annotations/README.md @@ -0,0 +1,10 @@ +## Hibernate 5 + +This module contains articles about Hibernate 5. + +### Relevant Articles: +- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) +- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) +- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) + diff --git a/persistence-modules/hibernate5-annotations/pom.xml b/persistence-modules/hibernate5-annotations/pom.xml new file mode 100644 index 0000000000..ab242333fe --- /dev/null +++ b/persistence-modules/hibernate5-annotations/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + hibernate5-annotations + 0.1-SNAPSHOT + hibernate5-annotations + jar + Hibernate tutorial illustrating the use of named parameters + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate-core.version} + + + + com.h2database + h2 + ${h2.version} + + + + org.apache.commons + commons-lang3 + ${commons.lang3.version} + + + + org.hibernate + hibernate-testing + ${hibernate-core.version} + + + + org.hibernate + hibernate-spatial + ${hibernate-core.version} + + + org.opengeo + geodb + ${geodb.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.4.7.Final + 1.4.200 + 3.8.1 + true + 2.1.7.RELEASE + 5.4.7.Final + 1.4.200 + 3.8.1 + 0.9 + + + diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..afe2aeac89 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +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; + +import com.baeldung.hibernate.joincolumn.Email; +import com.baeldung.hibernate.joincolumn.Office; +import com.baeldung.hibernate.joincolumn.OfficeAddress; + +public class HibernateUtil { + 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; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); + metadataSources.addAnnotatedClass(Email.class); + metadataSources.addAnnotatedClass(Office.class); + metadataSources.addAnnotatedClass(OfficeAddress.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.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-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java new file mode 100644 index 0000000000..d559e5a6c2 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java @@ -0,0 +1,69 @@ +package com.baeldung.hibernate.customtypes; + +import java.util.Objects; + +public class Address { + + private String addressLine1; + private String addressLine2; + private String city; + private String country; + private int zipCode; + + public String getAddressLine1() { + return addressLine1; + } + + public String getAddressLine2() { + return addressLine2; + } + + public String getCity() { + return city; + } + + public String getCountry() { + return country; + } + + public int getZipCode() { + return zipCode; + } + + public void setAddressLine1(String addressLine1) { + this.addressLine1 = addressLine1; + } + + public void setAddressLine2(String addressLine2) { + this.addressLine2 = addressLine2; + } + + public void setCity(String city) { + this.city = city; + } + + public void setCountry(String country) { + this.country = country; + } + + public void setZipCode(int zipCode) { + this.zipCode = zipCode; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Address address = (Address) o; + return zipCode == address.zipCode && + Objects.equals(addressLine1, address.addressLine1) && + Objects.equals(addressLine2, address.addressLine2) && + Objects.equals(city, address.city) && + Objects.equals(country, address.country); + } + + @Override + public int hashCode() { + return Objects.hash(addressLine1, addressLine2, city, country, zipCode); + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java new file mode 100644 index 0000000000..c10c67df9a --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java @@ -0,0 +1,169 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.type.IntegerType; +import org.hibernate.type.StringType; +import org.hibernate.type.Type; +import org.hibernate.usertype.CompositeUserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Objects; + +public class AddressType implements CompositeUserType { + + @Override + public String[] getPropertyNames() { + return new String[]{"addressLine1", "addressLine2", + "city", "country", "zipcode"}; + } + + @Override + public Type[] getPropertyTypes() { + return new Type[]{StringType.INSTANCE, StringType.INSTANCE, + StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE}; + } + + @Override + public Object getPropertyValue(Object component, int property) throws HibernateException { + + Address empAdd = (Address) component; + + switch (property) { + case 0: + return empAdd.getAddressLine1(); + case 1: + return empAdd.getAddressLine2(); + case 2: + return empAdd.getCity(); + case 3: + return empAdd.getCountry(); + case 4: + return Integer.valueOf(empAdd.getZipCode()); + } + + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); + } + + @Override + public void setPropertyValue(Object component, int property, Object value) throws HibernateException { + + Address empAdd = (Address) component; + + switch (property) { + case 0: + empAdd.setAddressLine1((String) value); + case 1: + empAdd.setAddressLine2((String) value); + case 2: + empAdd.setCity((String) value); + case 3: + empAdd.setCountry((String) value); + case 4: + empAdd.setZipCode((Integer) value); + } + + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); + + } + + @Override + public Class returnedClass() { + return Address.class; + } + + @Override + public boolean equals(Object x, Object y) throws HibernateException { + if (x == y) + return true; + + if (Objects.isNull(x) || Objects.isNull(y)) + return false; + + return x.equals(y); + } + + @Override + public int hashCode(Object x) throws HibernateException { + return x.hashCode(); + } + + @Override + public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { + + Address empAdd = new Address(); + empAdd.setAddressLine1(rs.getString(names[0])); + + if (rs.wasNull()) + return null; + + empAdd.setAddressLine2(rs.getString(names[1])); + empAdd.setCity(rs.getString(names[2])); + empAdd.setCountry(rs.getString(names[3])); + empAdd.setZipCode(rs.getInt(names[4])); + + return empAdd; + } + + @Override + public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { + + if (Objects.isNull(value)) + st.setNull(index, Types.VARCHAR); + else { + + Address empAdd = (Address) value; + st.setString(index, empAdd.getAddressLine1()); + st.setString(index + 1, empAdd.getAddressLine2()); + st.setString(index + 2, empAdd.getCity()); + st.setString(index + 3, empAdd.getCountry()); + st.setInt(index + 4, empAdd.getZipCode()); + } + } + + @Override + public Object deepCopy(Object value) throws HibernateException { + + if (Objects.isNull(value)) + return null; + + Address oldEmpAdd = (Address) value; + Address newEmpAdd = new Address(); + + newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1()); + newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2()); + newEmpAdd.setCity(oldEmpAdd.getCity()); + newEmpAdd.setCountry(oldEmpAdd.getCountry()); + newEmpAdd.setZipCode(oldEmpAdd.getZipCode()); + + return newEmpAdd; + } + + @Override + public boolean isMutable() { + return true; + } + + @Override + public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { + return (Serializable) deepCopy(value); + } + + @Override + public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { + return deepCopy(cached); + } + + @Override + public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { + return original; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java new file mode 100644 index 0000000000..56be9e693f --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.type.LocalDateType; +import org.hibernate.type.descriptor.WrapperOptions; +import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; +import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; +import org.hibernate.type.descriptor.java.MutabilityPlan; + +import java.time.LocalDate; + +public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { + + public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); + + public LocalDateStringJavaDescriptor() { + super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE); + } + + @Override + public String toString(LocalDate value) { + return LocalDateType.FORMATTER.format(value); + } + + @Override + public LocalDate fromString(String string) { + return LocalDate.from(LocalDateType.FORMATTER.parse(string)); + } + + @Override + public X unwrap(LocalDate value, Class type, WrapperOptions options) { + + if (value == null) + return null; + + if (String.class.isAssignableFrom(type)) + return (X) LocalDateType.FORMATTER.format(value); + + throw unknownUnwrap(type); + } + + @Override + public LocalDate wrap(X value, WrapperOptions options) { + if (value == null) + return null; + + if(String.class.isInstance(value)) + return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); + + throw unknownWrap(value.getClass()); + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java new file mode 100644 index 0000000000..c8d37073e8 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.dialect.Dialect; +import org.hibernate.type.AbstractSingleColumnStandardBasicType; +import org.hibernate.type.DiscriminatorType; +import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; +import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; + +import java.time.LocalDate; + +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { + + public static final LocalDateStringType INSTANCE = new LocalDateStringType(); + + public LocalDateStringType() { + super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + } + + @Override + public String getName() { + return "LocalDateString"; + } + + @Override + public LocalDate stringToObject(String xml) throws Exception { + return fromString(xml); + } + + @Override + public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { + return '\'' + toString(value) + '\''; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java new file mode 100644 index 0000000000..3ca06e4316 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java @@ -0,0 +1,88 @@ +package com.baeldung.hibernate.customtypes; + +import com.baeldung.hibernate.pojo.Phone; +import org.hibernate.annotations.Columns; +import org.hibernate.annotations.Parameter; +import org.hibernate.annotations.Type; +import org.hibernate.annotations.TypeDef; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; +import java.time.LocalDate; + +@TypeDef(name = "PhoneNumber", + typeClass = PhoneNumberType.class, + defaultForType = PhoneNumber.class) +@Entity +@Table(name = "OfficeEmployee") +public class OfficeEmployee { + + @Id + @GeneratedValue + private long id; + + @Column + @Type(type = "LocalDateString") + private LocalDate dateOfJoining; + + @Columns(columns = {@Column(name = "country_code"), + @Column(name = "city_code"), + @Column(name = "number")}) + private PhoneNumber employeeNumber; + + @Columns(columns = {@Column(name = "address_line_1"), + @Column(name = "address_line_2"), + @Column(name = "city"), @Column(name = "country"), + @Column(name = "zip_code")}) + @Type(type = "com.baeldung.hibernate.customtypes.AddressType") + private Address empAddress; + + @Type(type = "com.baeldung.hibernate.customtypes.SalaryType", + parameters = {@Parameter(name = "currency", value = "USD")}) + @Columns(columns = {@Column(name = "amount"), + @Column(name = "currency")}) + private Salary salary; + + public Salary getSalary() { + return salary; + } + + public void setSalary(Salary salary) { + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public LocalDate getDateOfJoining() { + return dateOfJoining; + } + + public void setDateOfJoining(LocalDate dateOfJoining) { + this.dateOfJoining = dateOfJoining; + } + + public PhoneNumber getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(PhoneNumber employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public Address getEmpAddress() { + return empAddress; + } + + public void setEmpAddress(Address empAddress) { + this.empAddress = empAddress; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java new file mode 100644 index 0000000000..0be6cbc910 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.customtypes; + +import java.util.Objects; + +public final class PhoneNumber { + + private final int countryCode; + private final int cityCode; + private final int number; + + public PhoneNumber(int countryCode, int cityCode, int number) { + this.countryCode = countryCode; + this.cityCode = cityCode; + this.number = number; + } + + public int getCountryCode() { + return countryCode; + } + + public int getCityCode() { + return cityCode; + } + + public int getNumber() { + return number; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PhoneNumber that = (PhoneNumber) o; + return countryCode == that.countryCode && + cityCode == that.cityCode && + number == that.number; + } + + @Override + public int hashCode() { + return Objects.hash(countryCode, cityCode, number); + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java new file mode 100644 index 0000000000..9f09352bec --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java @@ -0,0 +1,98 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Objects; + + +public class PhoneNumberType implements UserType { + @Override + public int[] sqlTypes() { + return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER}; + } + + @Override + public Class returnedClass() { + return PhoneNumber.class; + } + + @Override + public boolean equals(Object x, Object y) throws HibernateException { + if (x == y) + return true; + if (Objects.isNull(x) || Objects.isNull(y)) + return false; + + return x.equals(y); + } + + @Override + public int hashCode(Object x) throws HibernateException { + return x.hashCode(); + } + + @Override + public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { + int countryCode = rs.getInt(names[0]); + + if (rs.wasNull()) + return null; + + int cityCode = rs.getInt(names[1]); + int number = rs.getInt(names[2]); + PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number); + + return employeeNumber; + } + + @Override + public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { + + if (Objects.isNull(value)) { + st.setNull(index, Types.INTEGER); + } else { + PhoneNumber employeeNumber = (PhoneNumber) value; + st.setInt(index,employeeNumber.getCountryCode()); + st.setInt(index+1,employeeNumber.getCityCode()); + st.setInt(index+2,employeeNumber.getNumber()); + } + } + + @Override + public Object deepCopy(Object value) throws HibernateException { + if (Objects.isNull(value)) + return null; + + PhoneNumber empNumber = (PhoneNumber) value; + PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber()); + + return newEmpNumber; + } + + @Override + public boolean isMutable() { + return false; + } + + @Override + public Serializable disassemble(Object value) throws HibernateException { + return (Serializable) value; + } + + @Override + public Object assemble(Serializable cached, Object owner) throws HibernateException { + return cached; + } + + @Override + public Object replace(Object original, Object target, Object owner) throws HibernateException { + return original; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java new file mode 100644 index 0000000000..f9a7ac5902 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.customtypes; + +import java.util.Objects; + +public class Salary { + + private Long amount; + private String currency; + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Salary salary = (Salary) o; + return Objects.equals(amount, salary.amount) && + Objects.equals(currency, salary.currency); + } + + @Override + public int hashCode() { + return Objects.hash(amount, currency); + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java new file mode 100644 index 0000000000..340c697c11 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java @@ -0,0 +1,15 @@ +package com.baeldung.hibernate.customtypes; + +public class SalaryCurrencyConvertor { + + public static Long convert(Long amount, String oldCurr, String newCurr){ + if (newCurr.equalsIgnoreCase(oldCurr)) + return amount; + + return convertTo(); + } + + private static Long convertTo() { + return 10L; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java new file mode 100644 index 0000000000..266b85140b --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java @@ -0,0 +1,161 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.type.LongType; +import org.hibernate.type.StringType; +import org.hibernate.type.Type; +import org.hibernate.usertype.CompositeUserType; +import org.hibernate.usertype.DynamicParameterizedType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Objects; +import java.util.Properties; + +public class SalaryType implements CompositeUserType, DynamicParameterizedType { + + private String localCurrency; + + @Override + public String[] getPropertyNames() { + return new String[]{"amount", "currency"}; + } + + @Override + public Type[] getPropertyTypes() { + return new Type[]{LongType.INSTANCE, StringType.INSTANCE}; + } + + @Override + public Object getPropertyValue(Object component, int property) throws HibernateException { + + Salary salary = (Salary) component; + + switch (property) { + case 0: + return salary.getAmount(); + case 1: + return salary.getCurrency(); + } + + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); + + } + + + @Override + public void setPropertyValue(Object component, int property, Object value) throws HibernateException { + + Salary salary = (Salary) component; + + switch (property) { + case 0: + salary.setAmount((Long) value); + case 1: + salary.setCurrency((String) value); + } + + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); + + } + + @Override + public Class returnedClass() { + return Salary.class; + } + + @Override + public boolean equals(Object x, Object y) throws HibernateException { + + if (x == y) + return true; + + if (Objects.isNull(x) || Objects.isNull(y)) + return false; + + return x.equals(y); + + } + + @Override + public int hashCode(Object x) throws HibernateException { + return x.hashCode(); + } + + @Override + public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { + + Salary salary = new Salary(); + salary.setAmount(rs.getLong(names[0])); + + if (rs.wasNull()) + return null; + + salary.setCurrency(rs.getString(names[1])); + + return salary; + } + + @Override + public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { + + + if (Objects.isNull(value)) + st.setNull(index, Types.BIGINT); + else { + + Salary salary = (Salary) value; + st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(), + salary.getCurrency(), localCurrency)); + st.setString(index + 1, salary.getCurrency()); + } + } + + @Override + public Object deepCopy(Object value) throws HibernateException { + + if (Objects.isNull(value)) + return null; + + Salary oldSal = (Salary) value; + Salary newSal = new Salary(); + + newSal.setAmount(oldSal.getAmount()); + newSal.setCurrency(oldSal.getCurrency()); + + return newSal; + } + + @Override + public boolean isMutable() { + return true; + } + + @Override + public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { + return (Serializable) deepCopy(value); + } + + @Override + public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { + return deepCopy(cached); + } + + @Override + public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { + return original; + } + + @Override + public void setParameterValues(Properties parameters) { + this.localCurrency = parameters.getProperty("currency"); + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java new file mode 100644 index 0000000000..df07c3cf69 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.joincolumn; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Email { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String address; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "employee_id") + private OfficialEmployee employee; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public OfficialEmployee getEmployee() { + return employee; + } + + public void setEmployee(OfficialEmployee employee) { + this.employee = employee; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java new file mode 100644 index 0000000000..9940577761 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.joincolumn; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.ManyToOne; + +@Entity +public class Office { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumns({ + @JoinColumn(name="ADDR_ID", referencedColumnName="ID"), + @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP") + }) + private OfficeAddress address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public OfficeAddress getAddress() { + return address; + } + + public void setAddress(OfficeAddress address) { + this.address = address; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java new file mode 100644 index 0000000000..cc723db6a2 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.joincolumn; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class OfficeAddress { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "ZIP") + private String zipCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java new file mode 100644 index 0000000000..49c63c7578 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java @@ -0,0 +1,36 @@ +package com.baeldung.hibernate.joincolumn; + +import java.util.List; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class OfficialEmployee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee") + private List emails; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public List getEmails() { + return emails; + } + + public void setEmails(List emails) { + this.emails = emails; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5-annotations/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/main/resources/logback.xml b/persistence-modules/hibernate5-annotations/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java new file mode 100644 index 0000000000..63dc6330be --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java @@ -0,0 +1,90 @@ +package com.baeldung.hibernate.customtypes; + +import com.baeldung.hibernate.HibernateUtil; +import org.hibernate.SessionFactory; +import org.hibernate.query.Query; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.time.LocalDate; + +import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; + +public class HibernateCustomTypesManualTest { + + @Test + public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() throws IOException { + + final OfficeEmployee e = new OfficeEmployee(); + e.setDateOfJoining(LocalDate.now()); + + PhoneNumber number = new PhoneNumber(1, 222, 8781902); + e.setEmployeeNumber(number); + + Address empAdd = new Address(); + empAdd.setAddressLine1("Street"); + empAdd.setAddressLine2("Area"); + empAdd.setCity("City"); + empAdd.setCountry("Country"); + empAdd.setZipCode(100); + + e.setEmpAddress(empAdd); + + Salary empSalary = new Salary(); + empSalary.setAmount(1000L); + empSalary.setCurrency("USD"); + e.setSalary(empSalary); + + doInHibernate(this::sessionFactory, session -> { + session.save(e); + boolean contains = session.contains(e); + Assert.assertTrue(contains); + }); + + } + + @Test + public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() throws IOException { + + final OfficeEmployee e = new OfficeEmployee(); + e.setDateOfJoining(LocalDate.now()); + + PhoneNumber number = new PhoneNumber(1, 222, 8781902); + e.setEmployeeNumber(number); + + Address empAdd = new Address(); + empAdd.setAddressLine1("Street"); + empAdd.setAddressLine2("Area"); + empAdd.setCity("City"); + empAdd.setCountry("Country"); + empAdd.setZipCode(100); + e.setEmpAddress(empAdd); + + Salary empSalary = new Salary(); + empSalary.setAmount(1000L); + empSalary.setCurrency("USD"); + e.setSalary(empSalary); + + doInHibernate(this::sessionFactory, session -> { + session.save(e); + + Query query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode"); + query.setParameter("pinCode",100); + int size = query.list().size(); + + Assert.assertEquals(1, size); + }); + + } + + private SessionFactory sessionFactory() { + try { + return HibernateUtil.getSessionFactory("hibernate-customtypes.properties"); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java new file mode 100644 index 0000000000..0998ff1d90 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.joincolumn; + +import com.baeldung.hibernate.HibernateUtil; +import java.io.IOException; +import org.hibernate.Session; +import org.hibernate.Transaction; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + + +public class JoinColumnIntegrationTest { + + private Session session; + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenOfficeEntity_setAddress_shouldPersist() { + Office office = new Office(); + + OfficeAddress address = new OfficeAddress(); + address.setZipCode("11-111"); + office.setAddress(address); + + session.save(office); + session.flush(); + session.clear(); + } + + @Test + public void givenEmployeeEntity_setEmails_shouldPersist() { + OfficialEmployee employee = new OfficialEmployee(); + + Email email = new Email(); + email.setAddress("example@email.com"); + email.setEmployee(employee); + + session.save(employee); + session.flush(); + session.clear(); + } + +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate5-annotations/src/test/resources/hibernate-spatial.properties new file mode 100644 index 0000000000..1657c838e3 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/resources/hibernate-spatial.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect +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 diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/log4j.xml b/persistence-modules/hibernate5-annotations/src/test/resources/log4j.xml new file mode 100644 index 0000000000..2d153af124 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/resources/log4j.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/log4j2.xml b/persistence-modules/hibernate5-annotations/src/test/resources/log4j2.xml new file mode 100644 index 0000000000..c5d0f12462 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/resources/log4j2.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/logback.xml b/persistence-modules/hibernate5-annotations/src/test/resources/logback.xml new file mode 100644 index 0000000000..9e591977d7 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/resources/logback.xml @@ -0,0 +1,18 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/profile.png b/persistence-modules/hibernate5-annotations/src/test/resources/profile.png new file mode 100644 index 0000000000000000000000000000000000000000..1cd4e978b96d0f59a6e48692fcb68d1c6c565a20 GIT binary patch literal 1117 zcmV-j1fu(iP)%yyh@V&OYl(_AFwE`D&8)` zPnvkdvc#Z>pRh2kBHk{=qaGfCG;?<;rVe;D+%LyZS~!K}c+|op81YK@rzPHU@Th|m z4Dk`HcojTY;+}_-W%HGqKH@C!LiH8Tp>1lC@aTqoy zBU~QK<}hs@q|M8($ee`o<9#`B3-PL4Y7d9kW#<;n>t}6VNpYCswLrJTtEa_lFwgN$52-_vxvvfJs@B6-OYs%-@M_JTx*UfozG6(Bhs)>w z!pG%vU$b%f++EGa<#Tu1FZ^c#{;G|y5=kM3Y#X^mtSrFA_-o-vX7e_$5-udx(>S4U)i|4)(UJ~zR(vwE+6VTAzoo7wIS|c zh*yt`3wK%<+yX~Z9G1z2GQgf3~qx jc9u$WjpqGof00000NkvXXu0mjfJX<<= literal 0 HcmV?d00001 From 074dd3e986f44ebc0100103b381c64ee8d8c8bed Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:20:04 +0530 Subject: [PATCH 05/17] JAVA-4 : added new module hibernate-enterprise --- .../hibernate5-enterprise/README.md | 13 + .../hibernate5-enterprise/pom.xml | 76 ++++ .../com/baeldung/hibernate/HibernateUtil.java | 72 +++ .../UnsupportedTenancyException.java | 8 + .../hibernate/exception/EntityWithNoId.java | 16 + .../hibernate/exception/HibernateUtil.java | 63 +++ .../baeldung/hibernate/exception/Product.java | 40 ++ .../baeldung/hibernate/logging/Employee.java | 59 +++ .../baeldung/hibernate/pojo/PointEntity.java | 43 ++ .../hibernate/pojo/PolygonEntity.java | 38 ++ .../com/baeldung/hibernate/pojo/Student.java | 51 +++ .../baeldung/hibernateparameters/Event.java | 30 ++ .../main/resources/META-INF/persistence.xml | 18 + .../hibernateparameters/Event.hbm.xml | 15 + .../main/resources/hibernate-logging.cfg.xml | 27 ++ .../src/main/resources/hibernate.cfg.xml | 28 ++ .../src/main/resources/init_database.sql | 10 + .../src/main/resources/logback.xml | 13 + .../HibernateSpatialIntegrationTest.java | 161 +++++++ .../AggregateFunctionsIntegrationTest.java | 87 ++++ .../exception/HibernateExceptionUnitTest.java | 425 ++++++++++++++++++ .../HibernateLoggingIntegrationTest.java | 50 +++ .../baeldung/hibernate/multitenancy/Car.java | 26 ++ .../MultitenancyIntegrationTest.java | 104 +++++ ...seApproachMultitenancyIntegrationTest.java | 25 ++ .../MapMultiTenantConnectionProvider.java | 42 ++ .../multitenancy/database/TenantIdNames.java | 6 + ...maApproachMultitenancyIntegrationTest.java | 26 ++ .../SchemaMultiTenantConnectionProvider.java | 48 ++ .../multitenancy/schema/TenantIdNames.java | 6 + .../NamedParameterUnitTest.java | 73 +++ ...hibernate-database-multitenancy.properties | 2 + .../hibernate-database-mydb1.properties | 4 + .../hibernate-database-mydb2.properties | 4 + .../resources/hibernate-exception.properties | 16 + .../hibernate-schema-multitenancy.properties | 7 + .../resources/hibernate-spatial.properties | 14 + .../src/test/resources/hibernate.properties | 14 + .../src/test/resources/lifecycle-init.sql | 25 ++ .../src/test/resources/profile.png | Bin 0 -> 1117 bytes 40 files changed, 1785 insertions(+) create mode 100644 persistence-modules/hibernate5-enterprise/README.md create mode 100644 persistence-modules/hibernate5-enterprise/pom.xml create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java create mode 100644 persistence-modules/hibernate5-enterprise/src/main/resources/META-INF/persistence.xml create mode 100644 persistence-modules/hibernate5-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml create mode 100644 persistence-modules/hibernate5-enterprise/src/main/resources/hibernate-logging.cfg.xml create mode 100644 persistence-modules/hibernate5-enterprise/src/main/resources/hibernate.cfg.xml create mode 100644 persistence-modules/hibernate5-enterprise/src/main/resources/init_database.sql create mode 100644 persistence-modules/hibernate5-enterprise/src/main/resources/logback.xml create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-multitenancy.properties create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb1.properties create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb2.properties create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-exception.properties create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-schema-multitenancy.properties create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-spatial.properties create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/hibernate.properties create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/lifecycle-init.sql create mode 100644 persistence-modules/hibernate5-enterprise/src/test/resources/profile.png diff --git a/persistence-modules/hibernate5-enterprise/README.md b/persistence-modules/hibernate5-enterprise/README.md new file mode 100644 index 0000000000..994d8f062a --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/README.md @@ -0,0 +1,13 @@ +## Hibernate 5 + +This module contains articles about Hibernate 5. + +### Relevant articles: + +- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial) +- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy) +- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) +- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) +- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) +- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) +- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/pom.xml b/persistence-modules/hibernate5-enterprise/pom.xml new file mode 100644 index 0000000000..f12bb7e081 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + hibernate5-enterprise + 0.0.1-SNAPSHOT + hibernate5-enterprise + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + + + diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..ddeb1c42ea --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate; + +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; + +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + 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; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(PointEntity.class); + metadataSources.addAnnotatedClass(PolygonEntity.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.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-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java new file mode 100644 index 0000000000..989fa1281a --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/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-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java new file mode 100644 index 0000000000..ae5174ac9c --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/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-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java new file mode 100644 index 0000000000..031fa38de0 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/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-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java new file mode 100644 index 0000000000..9dcf4058a7 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.logging; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + public Employee() { + } + + public Employee(String name, String employeeNumber) { + this.name = name; + this.employeeNumber = employeeNumber; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java new file mode 100644 index 0000000000..736abde866 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Point; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PointEntity { + + @Id + @GeneratedValue + private Long id; + + @Column(columnDefinition="BINARY(2048)") + private Point point; + + public PointEntity() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Point getPoint() { + return point; + } + + public void setPoint(Point point) { + this.point = point; + } + + @Override + public String toString() { + return "PointEntity{" + "id=" + id + ", point=" + point + '}'; + } +} diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java new file mode 100644 index 0000000000..69208c8cd4 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Polygon; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PolygonEntity { + + @Id + @GeneratedValue + private Long id; + + private Polygon polygon; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Polygon getPolygon() { + return polygon; + } + + public void setPolygon(Polygon polygon) { + this.polygon = polygon; + } + + @Override + public String toString() { + return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}'; + } +} diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java new file mode 100644 index 0000000000..7912659a09 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java @@ -0,0 +1,30 @@ +package com.baeldung.hibernateparameters; + +public class Event { + private Long id; + + private String title; + + public Event() { + } + + public Event(String title) { + this.title = title; + } + + public Long getId() { + return id; + } + + private void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5-enterprise/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml b/persistence-modules/hibernate5-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml new file mode 100644 index 0000000000..c485080879 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate-logging.cfg.xml b/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate-logging.cfg.xml new file mode 100644 index 0000000000..52ef1ee685 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate-logging.cfg.xml @@ -0,0 +1,27 @@ + + + + + + + org.h2.Driver + jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1 + sa + + + 1 + + org.hibernate.dialect.H2Dialect + + org.hibernate.cache.internal.NoCacheProvider + + true + + create + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate.cfg.xml b/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate.cfg.xml new file mode 100644 index 0000000000..be564aaf5a --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,28 @@ + + + + + + + org.h2.Driver + jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1 + sa + + + 1 + + org.hibernate.dialect.H2Dialect + + org.hibernate.cache.internal.NoCacheProvider + + true + + create + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/init_database.sql b/persistence-modules/hibernate5-enterprise/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/logback.xml b/persistence-modules/hibernate5-enterprise/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java new file mode 100644 index 0000000000..74f752ab8c --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java @@ -0,0 +1,161 @@ +package com.baeldung.hibernate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import javax.persistence.Query; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; +import com.vividsolutions.jts.io.ParseException; +import com.vividsolutions.jts.io.WKTReader; +import com.vividsolutions.jts.util.GeometricShapeFactory; + +import geodb.GeoDB; + +public class HibernateSpatialIntegrationTest { + + private Session session; + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") + .openSession(); + transaction = session.beginTransaction(); + session.doWork(conn -> { GeoDB.InitGeoDB(conn); }); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void shouldConvertWktToGeometry() throws ParseException { + Geometry geometry = wktToGeometry("POINT (2 5)"); + assertEquals("Point", geometry.getGeometryType()); + assertTrue(geometry instanceof Point); + } + + @Test + public void shouldInsertAndSelectPoints() throws ParseException { + PointEntity entity = new PointEntity(); + entity.setPoint((Point) wktToGeometry("POINT (1 1)")); + + session.persist(entity); + PointEntity fromDb = session.find(PointEntity.class, entity.getId()); + assertEquals("POINT (1 1)", fromDb.getPoint().toString()); + } + + @Test + public void shouldSelectDisjointPoints() throws ParseException { + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Point point = (Point) wktToGeometry("POINT (3 4)"); + Query query = session.createQuery("select p from PointEntity p " + + "where disjoint(p.point, :point) = true", PointEntity.class); + query.setParameter("point", point); + assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString()); + assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString()); + } + + @Test + public void shouldSelectAllPointsWithinPolygon() throws ParseException { + insertPoint("POINT (1 1)"); + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true", + PointEntity.class); + query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))")); + assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) + .containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)"); + } + + @Test + public void shouldSelectAllPointsWithinRadius() throws ParseException { + insertPoint("POINT (1 1)"); + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true", + PointEntity.class); + query.setParameter("circle", createCircle(0.0, 0.0, 5)); + + assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) + .containsOnly("POINT (1 1)", "POINT (1 2)"); + } + + @Test + public void shouldSelectAdjacentPolygons() throws ParseException { + insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))"); + insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))"); + + Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true", + PolygonEntity.class); + query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))")); + assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString())) + .containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + } + + private void insertPoint(String point) throws ParseException { + PointEntity entity = new PointEntity(); + entity.setPoint((Point) wktToGeometry(point)); + session.persist(entity); + } + + private void insertPolygon(String polygon) throws ParseException { + PolygonEntity entity = new PolygonEntity(); + entity.setPolygon((Polygon) wktToGeometry(polygon)); + session.persist(entity); + } + + private Geometry wktToGeometry(String wellKnownText) throws ParseException { + WKTReader fromText = new WKTReader(); + Geometry geom = null; + geom = fromText.read(wellKnownText); + return geom; + } + + private static Geometry createCircle(double x, double y, double radius) { + GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); + shapeFactory.setNumPoints(32); + shapeFactory.setCentre(new Coordinate(x, y)); + shapeFactory.setSize(radius * 2); + return shapeFactory.createCircle(); + } + + public static Properties getProperties(String propertyFile) throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(propertyFile); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java new file mode 100644 index 0000000000..0b2bdf7ead --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.aggregatefunctions; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Student; + +public class AggregateFunctionsIntegrationTest { + + private static Session session; + private static Transaction transaction; + + @BeforeClass + public static final void setup() throws HibernateException, IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + + Student jonas = new Student("Jonas", 22); + session.save(jonas); + + Student sally = new Student("Sally", 20); + session.save(sally); + + Student simon = new Student("Simon", 25); + session.save(simon); + + Student raven = new Student("Raven", 21); + session.save(raven); + + Student sam = new Student("Sam", 23); + session.save(sam); + + } + + @AfterClass + public static final void teardown() { + if (session != null) { + transaction.rollback(); + session.close(); + } + } + + @Test + public void whenMaxAge_ThenReturnValue() { + int maxAge = (int) session.createQuery("SELECT MAX(age) from Student") + .getSingleResult(); + assertThat(maxAge).isEqualTo(25); + } + + @Test + public void whenMinAge_ThenReturnValue() { + int minAge = (int) session.createQuery("SELECT MIN(age) from Student") + .getSingleResult(); + assertThat(minAge).isEqualTo(20); + } + + @Test + public void whenAverageAge_ThenReturnValue() { + Double avgAge = (Double) session.createQuery("SELECT AVG(age) from Student") + .getSingleResult(); + assertThat(avgAge).isEqualTo(22.2); + } + + @Test + public void whenCountAll_ThenReturnValue() { + Long totalStudents = (Long) session.createQuery("SELECT COUNT(*) from Student") + .getSingleResult(); + assertThat(totalStudents).isEqualTo(5); + } + + @Test + public void whenSumOfAllAges_ThenReturnValue() { + Long sumOfAllAges = (Long) session.createQuery("SELECT SUM(age) from Student") + .getSingleResult(); + assertThat(sumOfAllAges).isEqualTo(111); + } +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java new file mode 100644 index 0000000000..3581c81daa --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/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-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java new file mode 100644 index 0000000000..f609c75834 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.logging; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.query.Query; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.logging.Employee; + +public class HibernateLoggingIntegrationTest { + + private SessionFactory sessionFactory; + + @Before + public void setUp() throws IOException { + final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate-logging.cfg.xml") + .build(); + try { + sessionFactory = new MetadataSources(registry).buildMetadata() + .buildSessionFactory(); + Session session = sessionFactory.openSession(); + session.beginTransaction(); + session.save(new Employee("John Smith", "001")); + session.getTransaction() + .commit(); + session.close(); + } catch (Exception e) { + fail(e); + StandardServiceRegistryBuilder.destroy(registry); + } + } + + @Test + public void whenAllEmployeesAreSelected_ThenSuccess() { + Query query = sessionFactory.openSession().createQuery("from com.baeldung.hibernate.logging.Employee", Employee.class); + List deptEmployees = query.list(); + Employee deptEmployee = deptEmployees.get(0); + assertEquals("John Smith", deptEmployee.getName()); + } +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java new file mode 100644 index 0000000000..1b6cee7e67 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.multitenancy; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity(name = "Car") +@Table(name = "Car") +public class Car implements Serializable { + + private static final long serialVersionUID = 1015320564683423342L; + + private String brand; + + @Id + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java new file mode 100644 index 0000000000..fdc3f9fa81 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java @@ -0,0 +1,104 @@ +package com.baeldung.hibernate.multitenancy; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.io.IOException; +import java.util.Properties; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.context.spi.CurrentTenantIdentifierResolver; +import org.hibernate.service.ServiceRegistry; +import org.junit.Before; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import com.baeldung.hibernate.multitenancy.database.TenantIdNames; + +public abstract class MultitenancyIntegrationTest { + + public abstract String getPropertyFile(); + + @Mock + private CurrentTenantIdentifierResolver currentTenantIdentifierResolver; + + private SessionFactory sessionFactory; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + Mockito.when(currentTenantIdentifierResolver.validateExistingCurrentSessions()) + .thenReturn(false); + + Properties properties = getHibernateProperties(); + properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver); + + sessionFactory = buildSessionFactory(properties); + + initTenant(TenantIdNames.MYDB1); + initTenant(TenantIdNames.MYDB2); + } + + protected void initTenant(String tenantId) { + whenCurrentTenantIs(tenantId); + createCarTable(); + } + + protected void whenCurrentTenantIs(String tenantId) { + Mockito.when(currentTenantIdentifierResolver.resolveCurrentTenantIdentifier()) + .thenReturn(tenantId); + } + + protected void whenAddCar(String brand) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + Car car = new Car(); + car.setBrand(brand); + session.save(car); + tx.commit(); + } + + protected void thenCarFound(String brand) { + Session session = sessionFactory.openSession(); + assertNotNull(session.get(Car.class, brand)); + } + + protected void thenCarNotFound(String brand) { + Session session = sessionFactory.openSession(); + assertNull(session.get(Car.class, brand)); + } + + @SuppressWarnings("deprecation") + private void createCarTable() { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + session.createSQLQuery("drop table Car if exists") + .executeUpdate(); + session.createSQLQuery("create table Car (brand varchar(255) primary key)") + .executeUpdate(); + tx.commit(); + } + + private Properties getHibernateProperties() throws IOException { + Properties properties = new Properties(); + properties.load(getClass().getResourceAsStream(getPropertyFile())); + return properties; + } + + private static SessionFactory buildSessionFactory(Properties properties) { + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Car.class); + return metadataSources.buildMetadata() + .buildSessionFactory(); + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java new file mode 100644 index 0000000000..92f477a646 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.multitenancy.database; + +import java.io.IOException; + +import org.junit.Test; + +import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; + +public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyIntegrationTest { + + @Override + public String getPropertyFile() { + return "/hibernate-database-multitenancy.properties"; + } + + @Test + public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException { + whenCurrentTenantIs(TenantIdNames.MYDB1); + whenAddCar("myCar"); + thenCarFound("myCar"); + whenCurrentTenantIs(TenantIdNames.MYDB2); + thenCarNotFound("myCar"); + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java new file mode 100644 index 0000000000..eb1f410622 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java @@ -0,0 +1,42 @@ +package com.baeldung.hibernate.multitenancy.database; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; +import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; + +@SuppressWarnings("serial") +public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { + + private final Map connectionProviderMap = new HashMap<>(); + + public MapMultiTenantConnectionProvider() throws IOException { + initConnectionProviderForTenant(TenantIdNames.MYDB1); + initConnectionProviderForTenant(TenantIdNames.MYDB2); + } + + @Override + protected ConnectionProvider getAnyConnectionProvider() { + return connectionProviderMap.values() + .iterator() + .next(); + } + + @Override + protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { + return connectionProviderMap.get(tenantIdentifier); + } + + private void initConnectionProviderForTenant(String tenantId) throws IOException { + Properties properties = new Properties(); + properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId))); + DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); + connectionProvider.configure(properties); + this.connectionProviderMap.put(tenantId, connectionProvider); + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java new file mode 100644 index 0000000000..231272fa63 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java @@ -0,0 +1,6 @@ +package com.baeldung.hibernate.multitenancy.database; + +public class TenantIdNames { + public static final String MYDB1 = "mydb1"; + public static final String MYDB2 = "mydb2"; +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java new file mode 100644 index 0000000000..304af65fca --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.multitenancy.schema; + +import java.io.IOException; + +import org.junit.Test; + +import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; +import com.baeldung.hibernate.multitenancy.database.TenantIdNames; + +public class SchemaApproachMultitenancyIntegrationTest extends MultitenancyIntegrationTest { + + @Override + public String getPropertyFile() { + return "/hibernate-schema-multitenancy.properties"; + } + + @Test + public void givenSchemaApproach_whenAddingEntries_thenOnlyAddedToConcreteSchema() throws IOException { + whenCurrentTenantIs(TenantIdNames.MYDB1); + whenAddCar("Ferrari"); + thenCarFound("Ferrari"); + whenCurrentTenantIs(TenantIdNames.MYDB2); + thenCarNotFound("Ferrari"); + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java new file mode 100644 index 0000000000..601eba651c --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.multitenancy.schema; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; + +import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; +import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; + +@SuppressWarnings("serial") +public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { + + private final ConnectionProvider connectionProvider; + + public SchemaMultiTenantConnectionProvider() throws IOException { + connectionProvider = initConnectionProvider(); + } + + @Override + protected ConnectionProvider getAnyConnectionProvider() { + return connectionProvider; + } + + @Override + protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { + return connectionProvider; + } + + @Override + public Connection getConnection(String tenantIdentifier) throws SQLException { + Connection connection = super.getConnection(tenantIdentifier); + connection.createStatement() + .execute(String.format("SET SCHEMA %s;", tenantIdentifier)); + return connection; + } + + private ConnectionProvider initConnectionProvider() throws IOException { + Properties properties = new Properties(); + properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties")); + + DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); + connectionProvider.configure(properties); + return connectionProvider; + } + +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java new file mode 100644 index 0000000000..2eba94e307 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java @@ -0,0 +1,6 @@ +package com.baeldung.hibernate.multitenancy.schema; + +public class TenantIdNames { + public static final String MYDB1 = "mydb1"; + public static final String MYDB2 = "mydb2"; +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java new file mode 100644 index 0000000000..4efa1e1f68 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernateparameters; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.query.Query; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +public class NamedParameterUnitTest { + private SessionFactory sessionFactory; + + @Before + public void setUp() throws Exception { + final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() + .configure() + .build(); + try { + sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); + Session session = sessionFactory.openSession(); + session.beginTransaction(); + session.save(new Event("Event 1")); + session.save(new Event("Event 2")); + session.getTransaction().commit(); + session.close(); + } catch (Exception e) { + fail(e); + StandardServiceRegistryBuilder.destroy(registry); + } + } + + @After + public void tearDown() throws Exception { + if (sessionFactory != null) { + sessionFactory.close(); + } + } + + @Test + public void whenNamedParameterProvided_thenCorrect() { + Session session = sessionFactory.openSession(); + session.beginTransaction(); + Query query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class); + + // This binds the value "Event1" to the parameter :eventTitle + query.setParameter("eventTitle", "Event 1"); + + assertEquals(1, query.list().size()); + session.getTransaction().commit(); + session.close(); + } + + @Test(expected = org.hibernate.QueryException.class) + public void whenNamedParameterMissing_thenThrowsQueryException() { + Session session = sessionFactory.openSession(); + session.beginTransaction(); + Query query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class); + + try { + query.list(); + fail("We are expecting an exception!"); + } finally { + session.getTransaction().commit(); + session.close(); + } + } +} diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-multitenancy.properties b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-multitenancy.properties new file mode 100644 index 0000000000..853fa80dfc --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-multitenancy.properties @@ -0,0 +1,2 @@ +hibernate.multiTenancy=DATABASE +hibernate.multi_tenant_connection_provider=com.baeldung.hibernate.multitenancy.database.MapMultiTenantConnectionProvider \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb1.properties b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb1.properties new file mode 100644 index 0000000000..345f1dbbea --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb1.properties @@ -0,0 +1,4 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb2.properties b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb2.properties new file mode 100644 index 0000000000..626b7853c6 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb2.properties @@ -0,0 +1,4 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb2;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-exception.properties new file mode 100644 index 0000000000..e08a23166d --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/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/hibernate5-enterprise/src/test/resources/hibernate-schema-multitenancy.properties b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-schema-multitenancy.properties new file mode 100644 index 0000000000..4abb621355 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-schema-multitenancy.properties @@ -0,0 +1,7 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS MYDB1\\;CREATE SCHEMA IF NOT EXISTS MYDB2\\; +hibernate.connection.username=sa +hibernate.connection.autocommit=true +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.multiTenancy=SCHEMA +hibernate.multi_tenant_connection_provider=com.baeldung.hibernate.multitenancy.schema.SchemaMultiTenantConnectionProvider \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-spatial.properties new file mode 100644 index 0000000000..1657c838e3 --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-spatial.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect +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 diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate.properties b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;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 diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate5-enterprise/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate5-enterprise/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/profile.png b/persistence-modules/hibernate5-enterprise/src/test/resources/profile.png new file mode 100644 index 0000000000000000000000000000000000000000..1cd4e978b96d0f59a6e48692fcb68d1c6c565a20 GIT binary patch literal 1117 zcmV-j1fu(iP)%yyh@V&OYl(_AFwE`D&8)` zPnvkdvc#Z>pRh2kBHk{=qaGfCG;?<;rVe;D+%LyZS~!K}c+|op81YK@rzPHU@Th|m z4Dk`HcojTY;+}_-W%HGqKH@C!LiH8Tp>1lC@aTqoy zBU~QK<}hs@q|M8($ee`o<9#`B3-PL4Y7d9kW#<;n>t}6VNpYCswLrJTtEa_lFwgN$52-_vxvvfJs@B6-OYs%-@M_JTx*UfozG6(Bhs)>w z!pG%vU$b%f++EGa<#Tu1FZ^c#{;G|y5=kM3Y#X^mtSrFA_-o-vX7e_$5-udx(>S4U)i|4)(UJ~zR(vwE+6VTAzoo7wIS|c zh*yt`3wK%<+yX~Z9G1z2GQgf3~qx jc9u$WjpqGof00000NkvXXu0mjfJX<<= literal 0 HcmV?d00001 From 0bb56912ff21f25c7386b6b2dc0e9350b2d31ac5 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:20:26 +0530 Subject: [PATCH 06/17] JAVA-4 : added new module hibernate5-jpa --- persistence-modules/hibernate5-jpa/README.md | 16 ++ persistence-modules/hibernate5-jpa/pom.xml | 95 +++++++++ .../com/baeldung/hibernate/HibernateUtil.java | 89 ++++++++ .../UnsupportedTenancyException.java | 8 + .../converters/PersonNameConverter.java | 61 ++++++ .../hibernate/entities/Department.java | 45 ++++ .../hibernate/entities/DeptEmployee.java | 83 ++++++++ .../jpabootstrap/application/Application.java | 34 +++ .../config/HibernatePersistenceUnitInfo.java | 131 ++++++++++++ .../config/JpaEntityManagerFactory.java | 69 ++++++ .../hibernate/jpabootstrap/entities/User.java | 45 ++++ .../service/EmployeeSearchService.java | 15 ++ .../service/EmployeeSearchServiceImpl.java | 77 +++++++ .../hibernate/onetoone/HibernateUtil.java | 61 ++++++ .../baeldung/hibernate/onetoone/Strategy.java | 25 +++ .../onetoone/foreignkeybased/Address.java | 60 ++++++ .../onetoone/foreignkeybased/User.java | 51 +++++ .../onetoone/jointablebased/Employee.java | 53 +++++ .../onetoone/jointablebased/WorkStation.java | 61 ++++++ .../onetoone/sharedkeybased/Address.java | 60 ++++++ .../onetoone/sharedkeybased/User.java | 50 +++++ .../OptimisticLockingCourse.java | 48 +++++ .../OptimisticLockingStudent.java | 70 ++++++ .../hibernate/pessimisticlocking/Address.java | 34 +++ .../pessimisticlocking/Customer.java | 58 +++++ .../pessimisticlocking/Individual.java | 49 +++++ .../PessimisticLockingCourse.java | 47 ++++ .../PessimisticLockingEmployee.java | 27 +++ .../PessimisticLockingStudent.java | 46 ++++ .../com/baeldung/hibernate/pojo/Movie.java | 52 +++++ .../com/baeldung/hibernate/pojo/Person.java | 32 +++ .../baeldung/hibernate/pojo/PersonName.java | 29 +++ .../com/baeldung/hibernate/pojo/Post.java | 59 ++++++ .../com/baeldung/hibernate/pojo/Student.java | 51 +++++ .../hibernate/transaction/PostService.java | 29 +++ .../PersistenceContextDemoApplication.java | 13 ++ .../persistencecontext/entity/User.java | 36 ++++ ...ExtendedPersistenceContextUserService.java | 33 +++ ...ansctionPersistenceContextUserService.java | 32 +++ .../main/resources/META-INF/persistence.xml | 19 ++ .../src/main/resources/init_database.sql | 10 + .../src/main/resources/logback.xml | 13 ++ .../PersonNameConverterUnitTest.java | 200 ++++++++++++++++++ .../EmployeeSearchServiceIntegrationTest.java | 121 +++++++++++ ...ToOneAnnotationFKBasedIntegrationTest.java | 80 +++++++ ...ToOneAnnotationJTBasedIntegrationTest.java | 80 +++++++ ...oOneAnnotationSPKBasedIntegrationTest.java | 79 +++++++ .../OptimisticLockingIntegrationTest.java | 146 +++++++++++++ ...asicPessimisticLockingIntegrationTest.java | 162 ++++++++++++++ .../PessimisticLockScopesIntegrationTest.java | 125 +++++++++++ .../TransactionIntegrationTest.java | 57 +++++ .../PersistenceContextIntegrationTest.java | 90 ++++++++ .../resources/hibernate-namedquery.properties | 9 + .../hibernate-pessimistic-locking.properties | 8 + .../src/test/resources/hibernate.properties | 14 ++ .../src/test/resources/profile.png | Bin 0 -> 1117 bytes 56 files changed, 3147 insertions(+) create mode 100644 persistence-modules/hibernate5-jpa/README.md create mode 100644 persistence-modules/hibernate5-jpa/pom.xml create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java create mode 100644 persistence-modules/hibernate5-jpa/src/main/resources/META-INF/persistence.xml create mode 100644 persistence-modules/hibernate5-jpa/src/main/resources/init_database.sql create mode 100644 persistence-modules/hibernate5-jpa/src/main/resources/logback.xml create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java create mode 100644 persistence-modules/hibernate5-jpa/src/test/resources/hibernate-namedquery.properties create mode 100644 persistence-modules/hibernate5-jpa/src/test/resources/hibernate-pessimistic-locking.properties create mode 100644 persistence-modules/hibernate5-jpa/src/test/resources/hibernate.properties create mode 100644 persistence-modules/hibernate5-jpa/src/test/resources/profile.png diff --git a/persistence-modules/hibernate5-jpa/README.md b/persistence-modules/hibernate5-jpa/README.md new file mode 100644 index 0000000000..bffba85d54 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/README.md @@ -0,0 +1,16 @@ +## Hibernate 5 + +This module contains articles about Hibernate 5. + +### Relevant articles: + +- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) +- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) +- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) +- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) +- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) +- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) +- [FetchMode in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-fetchmode) +- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) diff --git a/persistence-modules/hibernate5-jpa/pom.xml b/persistence-modules/hibernate5-jpa/pom.xml new file mode 100644 index 0000000000..b181fff36b --- /dev/null +++ b/persistence-modules/hibernate5-jpa/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + hibernate5-jpa + 0.0.1-SNAPSHOT + hibernate5-jpa + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-thymeleaf + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 1.21 + 2.1.7.RELEASE + + + diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..cf59fe4855 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate; + +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; + +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; +import com.baeldung.hibernate.pessimisticlocking.Individual; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + 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; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Person.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Individual.class); + metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); + metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); + metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); + metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); + metadataSources.addAnnotatedClass(Post.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.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-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java new file mode 100644 index 0000000000..506e674984 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.converters; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +import com.baeldung.hibernate.pojo.PersonName; + +@Converter +public class PersonNameConverter implements AttributeConverter { + + private static final String SEPARATOR = ", "; + + @Override + public String convertToDatabaseColumn(PersonName personName) { + if (personName == null) { + return null; + } + + StringBuilder sb = new StringBuilder(); + if (personName.getSurname() != null && !personName.getSurname() + .isEmpty()) { + sb.append(personName.getSurname()); + sb.append(SEPARATOR); + } + + if (personName.getName() != null && !personName.getName() + .isEmpty()) { + sb.append(personName.getName()); + } + + return sb.toString(); + } + + @Override + public PersonName convertToEntityAttribute(String dbPersonName) { + if (dbPersonName == null || dbPersonName.isEmpty()) { + return null; + } + + String[] pieces = dbPersonName.split(SEPARATOR); + + if (pieces == null || pieces.length == 0) { + return null; + } + + PersonName personName = new PersonName(); + String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null; + if (dbPersonName.contains(SEPARATOR)) { + personName.setSurname(firstPiece); + + if (pieces.length >= 2 && pieces[1] != null && !pieces[1].isEmpty()) { + personName.setName(pieces[1]); + } + } else { + personName.setName(firstPiece); + } + + return personName; + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java new file mode 100644 index 0000000000..f7b8e6bf6d --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.jpabootstrap.application; + +import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory; +import com.baeldung.hibernate.jpabootstrap.entities.User; +import javax.persistence.EntityManager; + +public class Application { + + public static void main(String[] args) { + EntityManager entityManager = getJpaEntityManager(); + User user = entityManager.find(User.class, 1); + System.out.println(user); + entityManager.getTransaction().begin(); + user.setName("John"); + user.setEmail("john@domain.com"); + entityManager.merge(user); + entityManager.getTransaction().commit(); + entityManager.getTransaction().begin(); + entityManager.persist(new User("Monica", "monica@domain.com")); + entityManager.getTransaction().commit(); + + // additional CRUD operations + + } + + private static class EntityManagerHolder { + private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory( + new Class[]{User.class}).getEntityManager(); + } + + public static EntityManager getJpaEntityManager() { + return EntityManagerHolder.ENTITY_MANAGER; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java new file mode 100644 index 0000000000..3852b44b64 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java @@ -0,0 +1,131 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import javax.sql.DataSource; +import javax.persistence.SharedCacheMode; +import javax.persistence.ValidationMode; +import javax.persistence.spi.ClassTransformer; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.PersistenceUnitTransactionType; +import org.hibernate.jpa.HibernatePersistenceProvider; + +public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo { + + public static final String JPA_VERSION = "2.1"; + private final String persistenceUnitName; + private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + private final List managedClassNames; + private final List mappingFileNames = new ArrayList<>(); + private final Properties properties; + private DataSource jtaDataSource; + private DataSource nonjtaDataSource; + private final List transformers = new ArrayList<>(); + + public HibernatePersistenceUnitInfo(String persistenceUnitName, List managedClassNames, Properties properties) { + this.persistenceUnitName = persistenceUnitName; + this.managedClassNames = managedClassNames; + this.properties = properties; + } + + @Override + public String getPersistenceUnitName() { + return persistenceUnitName; + } + + @Override + public String getPersistenceProviderClassName() { + return HibernatePersistenceProvider.class.getName(); + } + + @Override + public PersistenceUnitTransactionType getTransactionType() { + return transactionType; + } + + public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) { + this.jtaDataSource = jtaDataSource; + this.nonjtaDataSource = null; + transactionType = PersistenceUnitTransactionType.JTA; + return this; + } + + @Override + public DataSource getJtaDataSource() { + return jtaDataSource; + } + + public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) { + this.nonjtaDataSource = nonJtaDataSource; + this.jtaDataSource = null; + transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + return this; + } + + @Override + public DataSource getNonJtaDataSource() { + return nonjtaDataSource; + } + + @Override + public List getMappingFileNames() { + return mappingFileNames; + } + + @Override + public List getJarFileUrls() { + return Collections.emptyList(); + } + + @Override + public URL getPersistenceUnitRootUrl() { + return null; + } + + @Override + public List getManagedClassNames() { + return managedClassNames; + } + + @Override + public boolean excludeUnlistedClasses() { + return false; + } + + @Override + public SharedCacheMode getSharedCacheMode() { + return SharedCacheMode.UNSPECIFIED; + } + + @Override + public ValidationMode getValidationMode() { + return ValidationMode.AUTO; + } + + public Properties getProperties() { + return properties; + } + + @Override + public String getPersistenceXMLSchemaVersion() { + return JPA_VERSION; + } + + @Override + public ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + @Override + public void addTransformer(ClassTransformer transformer) { + transformers.add(transformer); + } + + @Override + public ClassLoader getNewTempClassLoader() { + return null; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java new file mode 100644 index 0000000000..bc1932af6f --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java @@ -0,0 +1,69 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import com.mysql.cj.jdbc.MysqlDataSource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.sql.DataSource; +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceUnitInfo; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; + +public class JpaEntityManagerFactory { + + private final String DB_URL = "jdbc:mysql://databaseurl"; + private final String DB_USER_NAME = "username"; + private final String DB_PASSWORD = "password"; + private final Class[] entityClasses; + + public JpaEntityManagerFactory(Class[] entityClasses) { + this.entityClasses = entityClasses; + } + + public EntityManager getEntityManager() { + return getEntityManagerFactory().createEntityManager(); + } + + protected EntityManagerFactory getEntityManagerFactory() { + PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName()); + Map configuration = new HashMap<>(); + return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration) + .build(); + } + + protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) { + return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties()); + } + + protected List getEntityClassNames() { + return Arrays.asList(getEntities()) + .stream() + .map(Class::getName) + .collect(Collectors.toList()); + } + + protected Properties getProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + properties.put("hibernate.id.new_generator_mappings", false); + properties.put("hibernate.connection.datasource", getMysqlDataSource()); + return properties; + } + + protected Class[] getEntities() { + return entityClasses; + } + + protected DataSource getMysqlDataSource() { + MysqlDataSource mysqlDataSource = new MysqlDataSource(); + mysqlDataSource.setURL(DB_URL); + mysqlDataSource.setUser(DB_USER_NAME); + mysqlDataSource.setPassword(DB_PASSWORD); + return mysqlDataSource; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java new file mode 100644 index 0000000000..86ca1dfa19 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.jpabootstrap.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + private String name; + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java new file mode 100644 index 0000000000..b7d1a537f0 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java @@ -0,0 +1,15 @@ +package com.baeldung.hibernate.jpacriteriabuilder.service; + +import java.util.List; + +import com.baeldung.hibernate.entities.DeptEmployee; + +public interface EmployeeSearchService { + + List filterbyTitleUsingCriteriaBuilder(List titles); + + List filterbyTitleUsingExpression(List titles); + + List searchByDepartmentQuery(String query); + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java new file mode 100644 index 0000000000..e79168a451 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java @@ -0,0 +1,77 @@ +package com.baeldung.hibernate.jpacriteriabuilder.service; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaBuilder.In; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import javax.persistence.criteria.Subquery; + +import com.baeldung.hibernate.entities.Department; +import com.baeldung.hibernate.entities.DeptEmployee; + +public class EmployeeSearchServiceImpl implements EmployeeSearchService { + + private EntityManager entityManager; + private CriteriaBuilder criteriaBuilder; + + public EmployeeSearchServiceImpl(EntityManager entityManager) { + this.entityManager = entityManager; + this.criteriaBuilder = entityManager.getCriteriaBuilder(); + + } + + @Override + public List filterbyTitleUsingCriteriaBuilder(List titles) { + CriteriaQuery criteriaQuery = createCriteriaQuery(DeptEmployee.class); + Root root = criteriaQuery.from(DeptEmployee.class); + In inClause = criteriaBuilder.in(root.get("title")); + for (String title : titles) { + inClause.value(title); + } + criteriaQuery.select(root) + .where(inClause); + TypedQuery query = entityManager.createQuery(criteriaQuery); + return query.getResultList(); + } + + @Override + public List filterbyTitleUsingExpression(List titles) { + CriteriaQuery criteriaQuery = createCriteriaQuery(DeptEmployee.class); + Root root = criteriaQuery.from(DeptEmployee.class); + criteriaQuery.select(root) + .where(root.get("title") + .in(titles)); + TypedQuery query = entityManager.createQuery(criteriaQuery); + return query.getResultList(); + } + + @Override + public List searchByDepartmentQuery(String searchKey) { + CriteriaQuery criteriaQuery = createCriteriaQuery(DeptEmployee.class); + Root emp = criteriaQuery.from(DeptEmployee.class); + + Subquery subquery = criteriaQuery.subquery(Department.class); + Root dept = subquery.from(Department.class); + subquery.select(dept) + .distinct(true) + .where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey) + .append("%") + .toString())); + + criteriaQuery.select(emp) + .where(criteriaBuilder.in(emp.get("department")) + .value(subquery)); + + TypedQuery query = entityManager.createQuery(criteriaQuery); + return query.getResultList(); + } + + private CriteriaQuery createCriteriaQuery(Class klass) { + return criteriaBuilder.createQuery(klass); + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java new file mode 100644 index 0000000000..18fa2a41db --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.onetoone; + +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(Strategy strategy) { + return buildSessionFactory(strategy); + } + + private static SessionFactory buildSessionFactory(Strategy strategy) { + try { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + for (Class entityClass : strategy.getEntityClasses()) { + metadataSources.addAnnotatedClass(entityClass); + } + + Metadata metadata = metadataSources.getMetadataBuilder() + .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-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java new file mode 100644 index 0000000000..3180566ca5 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.onetoone; + + +import java.util.Arrays; +import java.util.List; + +public enum Strategy { + //See that the classes belongs to different packages + FOREIGN_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.foreignkeybased.User.class, + com.baeldung.hibernate.onetoone.foreignkeybased.Address.class)), + SHARED_PRIMARY_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.sharedkeybased.User.class, + com.baeldung.hibernate.onetoone.sharedkeybased.Address.class)), + JOIN_TABLE_BASED(Arrays.asList(com.baeldung.hibernate.onetoone.jointablebased.Employee.class, + com.baeldung.hibernate.onetoone.jointablebased.WorkStation.class)); + + private List> entityClasses; + + Strategy(List> entityClasses) { + this.entityClasses = entityClasses; + } + + public List> getEntityClasses() { + return entityClasses; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java new file mode 100644 index 0000000000..e05eb46030 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.onetoone.foreignkeybased; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "address") +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "street") + private String street; + + @Column(name = "city") + private String city; + + @OneToOne(mappedBy = "address") + private User user; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java new file mode 100644 index 0000000000..dda972f29c --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.onetoone.foreignkeybased; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "username") + private String userName; + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "address_id", referencedColumnName = "id") + private Address address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java new file mode 100644 index 0000000000..a0bc101b9f --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.onetoone.jointablebased; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "employee") +public class Employee { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "ename") + private String name; + + @OneToOne(cascade = CascadeType.ALL) + @JoinTable(name = "emp_workstation", joinColumns = {@JoinColumn(name = "employee_id", referencedColumnName = "id")}, + inverseJoinColumns = {@JoinColumn(name = "workstation_id", referencedColumnName = "id")}) + private WorkStation workStation; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public WorkStation getWorkStation() { + return workStation; + } + + public void setWorkStation(WorkStation workStation) { + this.workStation = workStation; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java new file mode 100644 index 0000000000..f530611f6e --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.onetoone.jointablebased; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "workstation") +public class WorkStation { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "workstation_number") + private Integer workstationNumber; + + @Column(name = "floor") + private String floor; + + @OneToOne(mappedBy = "workStation") + private Employee employee; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getWorkstationNumber() { + return workstationNumber; + } + + public void setWorkstationNumber(Integer workstationNumber) { + this.workstationNumber = workstationNumber; + } + + public String getFloor() { + return floor; + } + + public void setFloor(String floor) { + this.floor = floor; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java new file mode 100644 index 0000000000..927516f6bb --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.onetoone.sharedkeybased; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.MapsId; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "address") +public class Address { + + @Id + @Column(name = "id") + private Long id; + + @Column(name = "street") + private String street; + + @Column(name = "city") + private String city; + + @OneToOne + @MapsId + private User user; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java new file mode 100644 index 0000000000..fa00db1271 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.onetoone.sharedkeybased; + + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "username") + private String userName; + + @OneToOne(mappedBy = "user", cascade = CascadeType.ALL) + private Address address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java new file mode 100644 index 0000000000..1af3e3e21b --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; + +@Entity +public class OptimisticLockingCourse { + + @Id + private Long id; + + private String name; + + @ManyToOne + @JoinTable(name = "optimistic_student_course") + private OptimisticLockingStudent student; + + public OptimisticLockingCourse(Long id, String name) { + this.id = id; + this.name = name; + } + + public OptimisticLockingCourse() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public OptimisticLockingStudent getStudent() { + return student; + } + + public void setStudent(OptimisticLockingStudent student) { + this.student = student; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java new file mode 100644 index 0000000000..b79212ae8d --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class OptimisticLockingStudent { + + @Id + private Long id; + + private String name; + + private String lastName; + @Version + private Integer version; + + @OneToMany(mappedBy = "student") + private List courses; + + public OptimisticLockingStudent(Long id, String name, String lastName, List courses) { + this.id = id; + this.name = name; + this.lastName = lastName; + this.courses = courses; + } + + public OptimisticLockingStudent() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java new file mode 100644 index 0000000000..c889cb6127 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.Embeddable; + +@Embeddable +public class Address { + + private String country; + private String city; + + public Address(String country, String city) { + this.country = country; + this.city = city; + } + + public Address() { + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java new file mode 100644 index 0000000000..cb73cbc958 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class Customer { + + @Id + private Long customerId; + private String name; + private String lastName; + @ElementCollection + @CollectionTable(name = "customer_address") + private List
addressList; + + public Customer() { + } + + public Customer(Long customerId, String name, String lastName, List
addressList) { + this.customerId = customerId; + this.name = name; + this.lastName = lastName; + this.addressList = addressList; + } + + public Long getCustomerId() { + return customerId; + } + + public void setCustomerId(Long customerId) { + this.customerId = customerId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List
getAddressList() { + return addressList; + } + + public void setAddressList(List
addressList) { + this.addressList = addressList; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java new file mode 100644 index 0000000000..e491c09eb5 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java @@ -0,0 +1,49 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Individual { + + @Id + private Long id; + private String name; + private String lastName; + + public Individual(Long id, String name, String lastName) { + this.id = id; + this.name = name; + this.lastName = lastName; + } + + public Individual() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java new file mode 100644 index 0000000000..aea7d5fc87 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.*; + +@Entity +public class PessimisticLockingCourse { + + @Id + private Long courseId; + private String name; + @ManyToOne + @JoinTable(name = "student_course") + private PessimisticLockingStudent student; + + public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) { + this.courseId = courseId; + this.name = name; + this.student = student; + } + + public PessimisticLockingCourse() { + } + + public Long getCourseId() { + return courseId; + } + + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public PessimisticLockingStudent getStudent() { + return student; + } + + public void setStudent(PessimisticLockingStudent students) { + this.student = students; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java new file mode 100644 index 0000000000..a1328cbdad --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.Entity; +import java.math.BigDecimal; + +@Entity +public class PessimisticLockingEmployee extends Individual { + + private BigDecimal salary; + + public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) { + super(id, name, lastName); + this.salary = salary; + } + + public PessimisticLockingEmployee() { + super(); + } + + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal average) { + this.salary = average; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java new file mode 100644 index 0000000000..e6c5f476b4 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class PessimisticLockingStudent { + + @Id + private Long id; + private String name; + @OneToMany(mappedBy = "student") + private List courses; + + public PessimisticLockingStudent(Long id, String name) { + this.id = id; + this.name = name; + } + + public PessimisticLockingStudent() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -0,0 +1,52 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "MOVIE") +public class Movie { + + @Id + private Long id; + + private String movieName; + + private Integer releaseYear; + + private String language; + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public Integer getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(Integer releaseYear) { + this.releaseYear = releaseYear; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java new file mode 100644 index 0000000000..390a5954ed --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java @@ -0,0 +1,32 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import com.baeldung.hibernate.converters.PersonNameConverter; + +@Entity(name = "PersonTable") +public class Person { + + @Id + @GeneratedValue + private Long id; + + @Convert(converter = PersonNameConverter.class) + private PersonName personName; + + public PersonName getPersonName() { + return personName; + } + + public void setPersonName(PersonName personName) { + this.personName = personName; + } + + public Long getId() { + return id; + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java new file mode 100644 index 0000000000..335fe73f75 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; + +public class PersonName implements Serializable { + + private static final long serialVersionUID = 7883094644631050150L; + + private String name; + + private String surname; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java new file mode 100644 index 0000000000..25e51e35d0 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "posts") +public class Post { + + @Id + @GeneratedValue + private int id; + + private String title; + + private String body; + + public Post() { } + + public Post(String title, String body) { + this.title = title; + this.body = body; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java new file mode 100644 index 0000000000..5a4eb20079 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.transaction; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.Query; + +public class PostService { + + + private Session session; + + public PostService(Session session) { + this.session = session; + } + + + public void updatePost(String title, String body, int id) { + Transaction txn = session.beginTransaction(); + Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3"); + updateQuery.setParameter(1, title); + updateQuery.setParameter(2, body); + updateQuery.setParameter(3, id); + updateQuery.executeUpdate(); + txn.commit(); + } + + + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java new file mode 100644 index 0000000000..17fa582e10 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.persistencecontext; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages="com.baeldung.persistencecontext") +public class PersistenceContextDemoApplication { + public static void main(String[] args) { + SpringApplication.run(PersistenceContextDemoApplication.class, args); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java new file mode 100644 index 0000000000..7252ac46f5 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java @@ -0,0 +1,36 @@ +package com.baeldung.persistencecontext.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class User { + + @Id + private Long id; + private String name; + private String role; + + public User() { + + } + + public User(Long id, String name, String role) { + this.id = id; + this.name = name; + this.role = role; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getRole() { + return role; + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java new file mode 100644 index 0000000000..ef25aac69f --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java @@ -0,0 +1,33 @@ +package com.baeldung.persistencecontext.service; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; +import javax.transaction.Transactional; + +import org.springframework.stereotype.Component; + +import com.baeldung.persistencecontext.entity.User; + +@Component +public class ExtendedPersistenceContextUserService { + + @PersistenceContext(type = PersistenceContextType.EXTENDED) + private EntityManager entityManager; + + @Transactional + public User insertWithTransaction(User user) { + entityManager.persist(user); + return user; + } + + public User insertWithoutTransaction(User user) { + entityManager.persist(user); + return user; + } + + public User find(long id) { + User user = entityManager.find(User.class, id); + return user; + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java new file mode 100644 index 0000000000..481defcf08 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java @@ -0,0 +1,32 @@ +package com.baeldung.persistencecontext.service; + + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.Transactional; + +import org.springframework.stereotype.Component; + +import com.baeldung.persistencecontext.entity.User; + +@Component +public class TransctionPersistenceContextUserService { + + @PersistenceContext + private EntityManager entityManager; + + @Transactional + public User insertWithTransaction(User user) { + entityManager.persist(user); + return user; + } + + public User insertWithoutTransaction(User user) { + entityManager.persist(user); + return user; + } + + public User find(long id) { + return entityManager.find(User.class, id); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5-jpa/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..4dfade1af3 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,19 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/main/resources/init_database.sql b/persistence-modules/hibernate5-jpa/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/main/resources/logback.xml b/persistence-modules/hibernate5-jpa/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java new file mode 100644 index 0000000000..3cd4761a7b --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java @@ -0,0 +1,200 @@ +package com.baeldung.hibernate.converter; + +import java.io.IOException; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.PersonName; + +import static org.junit.Assert.assertEquals; + +public class PersonNameConverterUnitTest { + + private Session session; + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + + session.createNativeQuery("delete from personTable") + .executeUpdate(); + + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenPersonName_WhenSaving_ThenNameAndSurnameConcat() { + final String name = "name"; + final String surname = "surname"; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals(surname + ", " + name, dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName() + .getName(), name); + assertEquals(dbPerson.getPersonName() + .getSurname(), surname); + } + + @Test + public void givenPersonNameNull_WhenSaving_ThenNullStored() { + final String name = null; + final String surname = null; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName(), null); + } + + @Test + public void givenPersonNameWithoutName_WhenSaving_ThenNotNameStored() { + final String name = null; + final String surname = "surname"; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("surname, ", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName() + .getName(), name); + assertEquals(dbPerson.getPersonName() + .getSurname(), surname); + } + + @Test + public void givenPersonNameWithoutSurName_WhenSaving_ThenNotSurNameStored() { + final String name = "name"; + final String surname = null; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("name", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName() + .getName(), name); + assertEquals(dbPerson.getPersonName() + .getSurname(), surname); + } + + @Test + public void givenPersonNameEmptyFields_WhenSaving_ThenFielsNotStored() { + final String name = ""; + final String surname = ""; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName(), null); + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java new file mode 100644 index 0000000000..2b12734a10 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java @@ -0,0 +1,121 @@ +package com.baeldung.hibernate.jpacriteriabuilder; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.entities.Department; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchService; +import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchServiceImpl; + +public class EmployeeSearchServiceIntegrationTest { + + private EntityManager entityManager; + private EmployeeSearchService searchService; + private Session session; + + @Before + public final void setup() throws HibernateException, IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + entityManager = session.getEntityManagerFactory() + .createEntityManager(); + searchService = new EmployeeSearchServiceImpl(entityManager); + + entityManager.getTransaction() + .begin(); + Department department = new Department("Pre Sales"); + DeptEmployee employee = new DeptEmployee("John Smith", "001", "Manager", department); + entityManager.persist(department); + entityManager.persist(employee); + employee = new DeptEmployee("Ian Evans", "002", "Associate", department); + entityManager.persist(department); + entityManager.persist(employee); + department = new Department("Copporate Sales"); + employee = new DeptEmployee("Robert Carter", "003", "Manager", department); + entityManager.persist(department); + entityManager.persist(employee); + employee = new DeptEmployee("John Carter", "004", "Senior Manager", department); + entityManager.persist(employee); + employee = new DeptEmployee("David Guetta", "009", "Associate", department); + entityManager.persist(department); + entityManager.persist(employee); + department = new Department("Post Sales"); + employee = new DeptEmployee("Robert Jonas", "005", "Director", department); + entityManager.persist(department); + entityManager.persist(employee); + employee = new DeptEmployee("John Ferros", "006", "Junior Associate", department); + entityManager.persist(department); + entityManager.persist(employee); + department = new Department("Client Support"); + employee = new DeptEmployee("Robert Mcclements", "007", "Director", department); + entityManager.persist(department); + entityManager.persist(employee); + employee = new DeptEmployee("Peter Parker", "008", "Manager", department); + entityManager.persist(department); + entityManager.persist(employee); + + } + + @After + public final void teardown() { + entityManager.getTransaction() + .rollback(); + entityManager.close(); + } + + @Test + public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() { + List titles = new ArrayList() { + { + add("Manager"); + add("Senior Manager"); + add("Director"); + } + }; + List result = searchService.filterbyTitleUsingCriteriaBuilder(titles); + assertEquals("Number of Employees does not match with expected.", 6, result.size()); + assertThat(result.stream() + .map(DeptEmployee::getTitle) + .distinct() + .collect(Collectors.toList()), containsInAnyOrder(titles.toArray())); + } + + @Test + public final void givenCriteriaQuery_whenSearchedUsingExpressionWithListofAuthors_thenResultIsFilteredByAuthorNames() { + List titles = new ArrayList() { + { + add("Manager"); + add("Senior Manager"); + add("Director"); + } + }; + List result = searchService.filterbyTitleUsingExpression(titles); + assertEquals("Number of Employees does not match with expected.", 6, result.size()); + assertThat(result.stream() + .map(DeptEmployee::getTitle) + .distinct() + .collect(Collectors.toList()), containsInAnyOrder(titles.toArray())); + } + + @Test + public final void givenCriteriaQuery_whenSearchedDepartmentLike_thenResultIsFilteredByDepartment() { + List result = searchService.searchByDepartmentQuery("Sales"); + assertEquals("Number of Employees does not match with expected.", 7, result.size()); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java new file mode 100644 index 0000000000..475c93f6ff --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.onetoone; + +import com.baeldung.hibernate.onetoone.foreignkeybased.Address; +import com.baeldung.hibernate.onetoone.foreignkeybased.User; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class HibernateOneToOneAnnotationFKBasedIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(Strategy.FOREIGN_KEY); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreates1to1relationship() { + User user = new User(); + user.setUserName("alice@baeldung.com"); + + Address address = new Address(); + address.setStreet("FK Street"); + address.setCity("FK City"); + + address.setUser(user); + user.setAddress(address); + + //Address entry will automatically be created by hibernate, since cascade type is specified as ALL + session.persist(user); + session.getTransaction().commit(); + + assert1to1InsertedData(); + } + + private void assert1to1InsertedData() { + @SuppressWarnings("unchecked") + List userList = session.createQuery("FROM User").list(); + + assertNotNull(userList); + assertEquals(1, userList.size()); + + User user = userList.get(0); + assertEquals("alice@baeldung.com", user.getUserName()); + + Address address = user.getAddress(); + assertNotNull(address); + assertEquals("FK Street", address.getStreet()); + assertEquals("FK City", address.getCity()); + + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java new file mode 100644 index 0000000000..df4cd4d137 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.onetoone; + +import com.baeldung.hibernate.onetoone.jointablebased.Employee; +import com.baeldung.hibernate.onetoone.jointablebased.WorkStation; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class HibernateOneToOneAnnotationJTBasedIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(Strategy.JOIN_TABLE_BASED); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreates1to1relationship() { + Employee employee = new Employee(); + employee.setName("bob@baeldung.com"); + + WorkStation workStation = new WorkStation(); + workStation.setWorkstationNumber(626); + workStation.setFloor("Sixth Floor"); + + + employee.setWorkStation(workStation); + workStation.setEmployee(employee); + + session.persist(employee); + session.getTransaction().commit(); + + assert1to1InsertedData(); + } + + private void assert1to1InsertedData() { + @SuppressWarnings("unchecked") + List employeeList = session.createQuery("FROM Employee").list(); + assertNotNull(employeeList); + assertEquals(1, employeeList.size()); + + Employee employee = employeeList.get(0); + assertEquals("bob@baeldung.com", employee.getName()); + + WorkStation workStation = employee.getWorkStation(); + + assertNotNull(workStation); + assertEquals((long) 626, (long) workStation.getWorkstationNumber()); + assertEquals("Sixth Floor", workStation.getFloor()); + + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java new file mode 100644 index 0000000000..7931a8e3fe --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java @@ -0,0 +1,79 @@ +package com.baeldung.hibernate.onetoone; + +import com.baeldung.hibernate.onetoone.sharedkeybased.Address; +import com.baeldung.hibernate.onetoone.sharedkeybased.User; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class HibernateOneToOneAnnotationSPKBasedIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(Strategy.SHARED_PRIMARY_KEY); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreates1to1relationship() { + User user = new User(); + user.setUserName("alice@baeldung.com"); + + Address address = new Address(); + address.setStreet("SPK Street"); + address.setCity("SPK City"); + + address.setUser(user); + user.setAddress(address); + + //Address entry will automatically be created by hibernate, since cascade type is specified as ALL + session.persist(user); + session.getTransaction().commit(); + + assert1to1InsertedData(); + } + + + private void assert1to1InsertedData() { + @SuppressWarnings("unchecked") + List userList = session.createQuery("FROM User").list(); + assertNotNull(userList); + assertEquals(1, userList.size()); + + User user = userList.get(0); + assertEquals("alice@baeldung.com", user.getUserName()); + + Address address = user.getAddress(); + assertNotNull(address); + assertEquals("SPK Street", address.getStreet()); + assertEquals("SPK City", address.getCity()); + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java new file mode 100644 index 0000000000..37c490f297 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -0,0 +1,146 @@ +package com.baeldung.hibernate.optimisticlocking; + +import java.io.IOException; +import java.util.Arrays; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.OptimisticLockException; + +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; + +public class OptimisticLockingIntegrationTest { + + private static SessionFactory sessionFactory; + + @Before + public void setUp() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH"); + OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course)); + course.setStudent(student); + entityManager.persist(course); + entityManager.persist(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @After + public void clean() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L); + OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L); + entityManager.remove(course); + entityManager.remove(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); + + return entityManager; + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java new file mode 100644 index 0000000000..4b9c7720fd --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java @@ -0,0 +1,162 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; +import com.vividsolutions.jts.util.Assert; + +import org.hibernate.SessionFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.persistence.*; +import java.io.IOException; +import java.util.Arrays; + +public class BasicPessimisticLockingIntegrationTest { + + private static SessionFactory sessionFactory; + + @BeforeClass + public static void setUp() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOHN"); + PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "MATH", student); + student.setCourses(Arrays.asList(course)); + entityManager.persist(course); + entityManager.persist(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @Test + public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + entityManager.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + Query query = entityManager.createQuery("from Student where studentId = :studentId"); + query.setParameter("studentId", 1L); + query.setLockMode(LockModeType.PESSIMISTIC_WRITE); + query.getResultList(); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + Query query2 = entityManager2.createQuery("from Student where studentId = :studentId"); + query2.setParameter("studentId", 1L); + query2.setLockMode(LockModeType.PESSIMISTIC_READ); + query2.getResultList(); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticReadLock_whenFindingNewOne_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_READ); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_FORCE_INCREMENT); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordAndRefreshWithPessimisticRead_whenFindingWithPessimisticWrite_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_WRITE); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticRead_whenUpdatingRecord_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_READ); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L); + resultStudent2.setName("Change"); + entityManager2.persist(resultStudent2); + entityManager2.getTransaction() + .commit(); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticWrite_whenUpdatingRecord_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_WRITE); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L); + resultStudent2.setName("Change"); + entityManager2.persist(resultStudent2); + entityManager2.getTransaction() + .commit(); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); + + return entityManager; + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java new file mode 100644 index 0000000000..81cb7d95f8 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java @@ -0,0 +1,125 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; + +import org.hibernate.SessionFactory; +import org.junit.AfterClass; +import org.junit.Test; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.PessimisticLockScope; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class PessimisticLockScopesIntegrationTest { + + private static SessionFactory sessionFactory; + + @Test + public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + PessimisticLockingEmployee employee = new PessimisticLockingEmployee(1L, "JOHN", "SMITH", new BigDecimal(4.5)); + em.persist(employee); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingEmployee foundEmployee = em2.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em3.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + @Test + public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + Address address = new Address("Poland", "Warsaw"); + Customer customer = new Customer(1L, "JOE", "DOE", Arrays.asList(address)); + em.persist(customer); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em2.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + @Test + public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOE"); + PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "COURSE", student); + student.setCourses(Arrays.asList(course)); + em.persist(course); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingCourse foundCourse = em2.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em3.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + protected EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); + + return entityManager; + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java new file mode 100644 index 0000000000..246a7d59f9 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.transaction; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.transaction.PostService; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; + +public class TransactionIntegrationTest { + + private static PostService postService; + private static Session session; + private static Logger logger = LoggerFactory.getLogger(TransactionIntegrationTest.class); + + @BeforeClass + public static void init() throws IOException { + Properties properties = new Properties(); + properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); + properties.setProperty("hibernate.connection.url", "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); + properties.setProperty("hibernate.connection.username", "sa"); + properties.setProperty("hibernate.show_sql", "true"); + properties.setProperty("jdbc.password", ""); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); + SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties); + session = sessionFactory.openSession(); + postService = new PostService(session); + } + + @Test + public void givenTitleAndBody_whenRepositoryUpdatePost_thenUpdatePost() { + + Post post = new Post("This is a title", "This is a sample post"); + session.persist(post); + + String title = "[UPDATE] Java HowTos"; + String body = "This is an updated posts on Java how-tos"; + postService.updatePost(title, body, post.getId()); + + session.refresh(post); + + assertEquals(post.getTitle(), title); + assertEquals(post.getBody(), body); + } + + +} diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java new file mode 100644 index 0000000000..b299dd5834 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java @@ -0,0 +1,90 @@ +package com.baeldung.persistencecontext; + +import com.baeldung.persistencecontext.entity.User; +import com.baeldung.persistencecontext.service.ExtendedPersistenceContextUserService; +import com.baeldung.persistencecontext.service.TransctionPersistenceContextUserService; + +import javax.persistence.EntityExistsException; +import javax.persistence.TransactionRequiredException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = com.baeldung.persistencecontext.PersistenceContextDemoApplication.class) +public class PersistenceContextIntegrationTest { + + @Autowired + private TransctionPersistenceContextUserService transctionPersistenceContext; + @Autowired + private ExtendedPersistenceContextUserService extendedPersistenceContext; + + @Test + public void testThatWhenUserSavedWithTransctionPersistenceContextThenUserShouldGetSavedInDB() { + User user = new User(121L, "Devender", "admin"); + transctionPersistenceContext.insertWithTransaction(user); + + User userFromTransctionPersistenceContext = transctionPersistenceContext.find(user.getId()); + assertNotNull(userFromTransctionPersistenceContext); + + User userFromExtendedPersistenceContext = extendedPersistenceContext.find(user.getId()); + assertNotNull(userFromExtendedPersistenceContext); + } + + @Test(expected = TransactionRequiredException.class) + public void testThatUserSaveWithoutTransactionThrowException() { + User user = new User(122L, "Devender", "admin"); + transctionPersistenceContext.insertWithoutTransaction(user); + } + + @Test + public void testThatWhenUserSavedWithExtendedPersistenceContextWithoutTransactionThenUserShouldGetCached() { + User user = new User(123L, "Devender", "admin"); + extendedPersistenceContext.insertWithoutTransaction(user); + + User userFromExtendedPersistenceContext = extendedPersistenceContext.find(user.getId()); + assertNotNull(userFromExtendedPersistenceContext); + + User userFromTransctionPersistenceContext = transctionPersistenceContext.find(user.getId()); + assertNull(userFromTransctionPersistenceContext); + } + + @Test(expected = EntityExistsException.class) + public void testThatPersistUserWithSameIdentifierThrowException() { + User user1 = new User(126L, "Devender", "admin"); + User user2 = new User(126L, "Devender", "admin"); + extendedPersistenceContext.insertWithoutTransaction(user1); + extendedPersistenceContext.insertWithoutTransaction(user2); + } + + @Test + public void testThatWhenUserSavedWithExtendedPersistenceContextWithTransactionThenUserShouldSaveEntityIntoDB() { + User user = new User(127L, "Devender", "admin"); + extendedPersistenceContext.insertWithTransaction(user); + + User userFromDB = transctionPersistenceContext.find(user.getId()); + assertNotNull(userFromDB); + } + + @Test + public void testThatWhenUserSavedWithExtendedPersistenceContextWithTransactionThenUserShouldFlushCachedEntityIntoDB() { + User user1 = new User(124L, "Devender", "admin"); + extendedPersistenceContext.insertWithoutTransaction(user1); + + User user2 = new User(125L, "Devender", "admin"); + extendedPersistenceContext.insertWithTransaction(user2); + + User user1FromTransctionPersistenceContext = transctionPersistenceContext.find(user1.getId()); + assertNotNull(user1FromTransctionPersistenceContext); + + User user2FromTransctionPersistenceContext = transctionPersistenceContext.find(user2.getId()); + assertNotNull(user2FromTransctionPersistenceContext); + } + +} diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-namedquery.properties new file mode 100644 index 0000000000..457f965347 --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-namedquery.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' +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 \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-pessimistic-locking.properties new file mode 100644 index 0000000000..4f1ff5e93a --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-pessimistic-locking.properties @@ -0,0 +1,8 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE +hibernate.connection.username=sa +hibernate.connection.autocommit=true +hibernate.dialect=org.hibernate.dialect.H2Dialect + +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/hibernate.properties b/persistence-modules/hibernate5-jpa/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate5-jpa/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;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 diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/profile.png b/persistence-modules/hibernate5-jpa/src/test/resources/profile.png new file mode 100644 index 0000000000000000000000000000000000000000..1cd4e978b96d0f59a6e48692fcb68d1c6c565a20 GIT binary patch literal 1117 zcmV-j1fu(iP)%yyh@V&OYl(_AFwE`D&8)` zPnvkdvc#Z>pRh2kBHk{=qaGfCG;?<;rVe;D+%LyZS~!K}c+|op81YK@rzPHU@Th|m z4Dk`HcojTY;+}_-W%HGqKH@C!LiH8Tp>1lC@aTqoy zBU~QK<}hs@q|M8($ee`o<9#`B3-PL4Y7d9kW#<;n>t}6VNpYCswLrJTtEa_lFwgN$52-_vxvvfJs@B6-OYs%-@M_JTx*UfozG6(Bhs)>w z!pG%vU$b%f++EGa<#Tu1FZ^c#{;G|y5=kM3Y#X^mtSrFA_-o-vX7e_$5-udx(>S4U)i|4)(UJ~zR(vwE+6VTAzoo7wIS|c zh*yt`3wK%<+yX~Z9G1z2GQgf3~qx jc9u$WjpqGof00000NkvXXu0mjfJX<<= literal 0 HcmV?d00001 From 9f8e1b51b3d5fad0f3499120e2bd41a96c0de3c2 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:20:46 +0530 Subject: [PATCH 07/17] JAVA-4 : added new module hibernate5-mapping --- .../hibernate5-mapping/README.md | 11 + .../hibernate5-mapping/pom.xml | 76 +++++++ .../com/baeldung/hibernate/HibernateUtil.java | 96 +++++++++ .../hibernate/entities/Department.java | 45 ++++ .../hibernate/entities/DeptEmployee.java | 83 ++++++++ .../hibernate/lob/HibernateSessionUtil.java | 61 ++++++ .../baeldung/hibernate/lob/model/User.java | 46 +++++ .../com/baeldung/hibernate/pojo/Employee.java | 87 ++++++++ .../hibernate/pojo/EntityDescription.java | 55 +++++ .../com/baeldung/hibernate/pojo/Phone.java | 50 +++++ .../com/baeldung/hibernate/pojo/Result.java | 31 +++ .../hibernate/pojo/TemporalValues.java | 195 ++++++++++++++++++ .../hibernate/pojo/generator/MyGenerator.java | 41 ++++ .../hibernate/pojo/inheritance/Animal.java | 40 ++++ .../hibernate/pojo/inheritance/Bag.java | 38 ++++ .../hibernate/pojo/inheritance/Book.java | 27 +++ .../hibernate/pojo/inheritance/Car.java | 25 +++ .../hibernate/pojo/inheritance/Item.java | 5 + .../pojo/inheritance/MyEmployee.java | 22 ++ .../hibernate/pojo/inheritance/MyProduct.java | 47 +++++ .../hibernate/pojo/inheritance/Pen.java | 27 +++ .../hibernate/pojo/inheritance/Person.java | 38 ++++ .../hibernate/pojo/inheritance/Pet.java | 27 +++ .../hibernate/pojo/inheritance/Vehicle.java | 40 ++++ .../baeldung/hibernate/pojo/package-info.java | 9 + .../main/resources/META-INF/persistence.xml | 18 ++ .../src/main/resources/logback.xml | 13 ++ .../hibernate/CustomClassIntegrationTest.java | 78 +++++++ .../DynamicMappingIntegrationTest.java | 160 ++++++++++++++ .../InheritanceMappingIntegrationTest.java | 89 ++++++++ .../hibernate/TemporalValuesUnitTest.java | 128 ++++++++++++ .../baeldung/hibernate/lob/LobUnitTest.java | 61 ++++++ .../src/test/resources/hibernate.properties | 14 ++ .../src/test/resources/lifecycle-init.sql | 25 +++ .../src/test/resources/profile.png | Bin 0 -> 1117 bytes 35 files changed, 1808 insertions(+) create mode 100644 persistence-modules/hibernate5-mapping/README.md create mode 100644 persistence-modules/hibernate5-mapping/pom.xml create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java create mode 100644 persistence-modules/hibernate5-mapping/src/main/resources/META-INF/persistence.xml create mode 100644 persistence-modules/hibernate5-mapping/src/main/resources/logback.xml create mode 100644 persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java create mode 100644 persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java create mode 100644 persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java create mode 100644 persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java create mode 100644 persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java create mode 100644 persistence-modules/hibernate5-mapping/src/test/resources/hibernate.properties create mode 100644 persistence-modules/hibernate5-mapping/src/test/resources/lifecycle-init.sql create mode 100644 persistence-modules/hibernate5-mapping/src/test/resources/profile.png diff --git a/persistence-modules/hibernate5-mapping/README.md b/persistence-modules/hibernate5-mapping/README.md new file mode 100644 index 0000000000..f18b0b63de --- /dev/null +++ b/persistence-modules/hibernate5-mapping/README.md @@ -0,0 +1,11 @@ +## Hibernate 5 + +This module contains articles about Hibernate 5. + +### Relevant articles: + +- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) +- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) +- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) +- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) +- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/pom.xml b/persistence-modules/hibernate5-mapping/pom.xml new file mode 100644 index 0000000000..59e0547671 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + hibernate5-mapping + 0.0.1-SNAPSHOT + hibernate5-mapping + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + + + diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..28e1af49ed --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,96 @@ +package com.baeldung.hibernate; + +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; + +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + +public class HibernateUtil { + 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; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.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-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java new file mode 100644 index 0000000000..dc5242ee7c --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.lob; + +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; + +import com.baeldung.hibernate.lob.model.User; + +public class HibernateSessionUtil { + + 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(User.class); + + Metadata metadata = metadataSources.buildMetadata(); + 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.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java new file mode 100644 index 0000000000..21f725b388 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.lob.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; + +@Entity +@Table(name="user") +public class User { + + @Id + private String id; + + @Column(name = "name", columnDefinition="VARCHAR(128)") + private String name; + + @Lob + @Column(name = "photo", columnDefinition="BLOB") + private byte[] photo; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public byte[] getPhoto() { + return photo; + } + + public void setPhoto(byte[] photo) { + this.photo = photo; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java new file mode 100644 index 0000000000..e9732b2b67 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.*; + +import javax.persistence.Entity; +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Where(clause = "deleted = false") +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") +public class Employee implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private long grossIncome; + + private int taxInPercents; + + private boolean deleted; + + public long getTaxJavaWay() { + return grossIncome * taxInPercents / 100; + } + + @Formula("grossIncome * taxInPercents / 100") + private long tax; + + @OneToMany + @JoinColumn(name = "employee_id") + @Where(clause = "deleted = false") + private Set phones = new HashSet<>(0); + + public Employee() { + } + + public Employee(long grossIncome, int taxInPercents) { + this.grossIncome = grossIncome; + this.taxInPercents = taxInPercents; + } + + public Integer getId() { + return id; + } + + public long getGrossIncome() { + return grossIncome; + } + + public int getTaxInPercents() { + return taxInPercents; + } + + public long getTax() { + return tax; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setGrossIncome(long grossIncome) { + this.grossIncome = grossIncome; + } + + public void setTaxInPercents(int taxInPercents) { + this.taxInPercents = taxInPercents; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Set getPhones() { + return phones; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java new file mode 100644 index 0000000000..131bb73a80 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -0,0 +1,55 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.Any; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class EntityDescription implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private String description; + + @Any( + metaDef = "EntityDescriptionMetaDef", + metaColumn = @Column(name = "entity_type") + ) + @JoinColumn(name = "entity_id") + private Serializable entity; + + public EntityDescription() { + } + + public EntityDescription(String description, Serializable entity) { + this.description = description; + this.entity = entity; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Serializable getEntity() { + return entity; + } + + public void setEntity(Serializable entity) { + this.entity = entity; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java new file mode 100644 index 0000000000..607269a267 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +public class Result { + private String employeeName; + + private String departmentName; + + public Result(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public Result() { + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java new file mode 100644 index 0000000000..f3fe095cae --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -0,0 +1,195 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.*; +import java.util.Calendar; + +@Entity +public class TemporalValues implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Basic + private java.sql.Date sqlDate; + + @Basic + private java.sql.Time sqlTime; + + @Basic + private java.sql.Timestamp sqlTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Date utilDate; + + @Basic + @Temporal(TemporalType.TIME) + private java.util.Date utilTime; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Date utilTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Calendar calendarDate; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Calendar calendarTimestamp; + + @Basic + private java.time.LocalDate localDate; + + @Basic + private java.time.LocalTime localTime; + + @Basic + private java.time.OffsetTime offsetTime; + + @Basic + private java.time.Instant instant; + + @Basic + private java.time.LocalDateTime localDateTime; + + @Basic + private java.time.OffsetDateTime offsetDateTime; + + @Basic + private java.time.ZonedDateTime zonedDateTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Time getSqlTime() { + return sqlTime; + } + + public void setSqlTime(Time sqlTime) { + this.sqlTime = sqlTime; + } + + public Timestamp getSqlTimestamp() { + return sqlTimestamp; + } + + public void setSqlTimestamp(Timestamp sqlTimestamp) { + this.sqlTimestamp = sqlTimestamp; + } + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.util.Date getUtilTime() { + return utilTime; + } + + public void setUtilTime(java.util.Date utilTime) { + this.utilTime = utilTime; + } + + public java.util.Date getUtilTimestamp() { + return utilTimestamp; + } + + public void setUtilTimestamp(java.util.Date utilTimestamp) { + this.utilTimestamp = utilTimestamp; + } + + public Calendar getCalendarDate() { + return calendarDate; + } + + public void setCalendarDate(Calendar calendarDate) { + this.calendarDate = calendarDate; + } + + public Calendar getCalendarTimestamp() { + return calendarTimestamp; + } + + public void setCalendarTimestamp(Calendar calendarTimestamp) { + this.calendarTimestamp = calendarTimestamp; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java new file mode 100644 index 0000000000..6fe7f915fc --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Animal { + + @Id + private long animalId; + + private String species; + + public Animal() {} + + public Animal(long animalId, String species) { + this.animalId = animalId; + this.species = species; + } + + public long getAnimalId() { + return animalId; + } + + public void setAnimalId(long animalId) { + this.animalId = animalId; + } + + public String getSpecies() { + return species; + } + + public void setSpecies(String species) { + this.species = species; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java new file mode 100644 index 0000000000..fa6e1b4bef --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +@Entity +@Polymorphism(type = PolymorphismType.EXPLICIT) +public class Bag implements Item { + + @Id + private long bagId; + + private String type; + + public Bag(long bagId, String type) { + this.bagId = bagId; + this.type = type; + } + + public long getBagId() { + return bagId; + } + + public void setBagId(long bagId) { + this.bagId = bagId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java new file mode 100644 index 0000000000..36ca8dd77c --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("1") +public class Book extends MyProduct { + private String author; + + public Book() { + } + + public Book(long productId, String name, String author) { + super(productId, name); + this.author = author; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java new file mode 100644 index 0000000000..49d1f7749a --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class Car extends Vehicle { + private String engine; + + public Car() { + } + + public Car(long vehicleId, String manufacturer, String engine) { + super(vehicleId, manufacturer); + this.engine = engine; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java new file mode 100644 index 0000000000..9656030736 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java @@ -0,0 +1,5 @@ +package com.baeldung.hibernate.pojo.inheritance; + +public interface Item { + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java new file mode 100644 index 0000000000..9a6bce16cf --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -0,0 +1,22 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class MyEmployee extends Person { + private String company; + + public MyEmployee(long personId, String name, String company) { + super(personId, name); + this.company = company; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java new file mode 100644 index 0000000000..13f04d8904 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +import org.hibernate.annotations.DiscriminatorFormula; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER) +// @DiscriminatorFormula("case when author is not null then 1 else 2 end") +public class MyProduct { + @Id + private long productId; + + private String name; + + public MyProduct() { + } + + public MyProduct(long productId, String name) { + super(); + this.productId = productId; + this.name = name; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java new file mode 100644 index 0000000000..32b77e52af --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("2") +public class Pen extends MyProduct { + private String color; + + public Pen() { + } + + public Pen(long productId, String name, String color) { + super(productId, name); + this.color = color; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java new file mode 100644 index 0000000000..99084b88af --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public class Person { + + @Id + private long personId; + + private String name; + + public Person() { + } + + public Person(long personId, String name) { + this.personId = personId; + this.name = name; + } + + public long getPersonId() { + return personId; + } + + public void setPersonId(long personId) { + this.personId = personId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java new file mode 100644 index 0000000000..870b3cd684 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.PrimaryKeyJoinColumn; + +@Entity +@PrimaryKeyJoinColumn(name = "petId") +public class Pet extends Animal { + private String name; + + public Pet() { + } + + public Pet(long animalId, String species, String name) { + super(animalId, species); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java new file mode 100644 index 0000000000..b2a920573e --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) +public class Vehicle { + @Id + private long vehicleId; + + private String manufacturer; + + public Vehicle() { + } + + public Vehicle(long vehicleId, String manufacturer) { + this.vehicleId = vehicleId; + this.manufacturer = manufacturer; + } + + public long getVehicleId() { + return vehicleId; + } + + public void setVehicleId(long vehicleId) { + this.vehicleId = vehicleId; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java new file mode 100644 index 0000000000..992cda7c1d --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java @@ -0,0 +1,9 @@ +@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", + metaValues = { + @MetaValue(value = "Employee", targetEntity = Employee.class), + @MetaValue(value = "Phone", targetEntity = Phone.class) + }) +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5-mapping/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/src/main/resources/logback.xml b/persistence-modules/hibernate5-mapping/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java new file mode 100644 index 0000000000..699890c457 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java @@ -0,0 +1,78 @@ +package com.baeldung.hibernate; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; + +import com.baeldung.hibernate.entities.DeptEmployee; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.Query; +import org.hibernate.transform.Transformers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.baeldung.hibernate.entities.Department; +import com.baeldung.hibernate.pojo.Result; + +public class CustomClassIntegrationTest { + + private Session session; + + private Transaction transaction; + + @BeforeEach + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + session.createNativeQuery("delete from department").executeUpdate(); + Department department = new Department("Sales"); + DeptEmployee employee = new DeptEmployee("John Smith", "001", department); + session.persist(department); + session.persist(employee); + transaction.commit(); + transaction = session.beginTransaction(); + } + + @Test + public void whenAllManagersAreSelected_ThenObjectGraphIsReturned() { + Query query = session.createQuery("from com.baeldung.hibernate.entities.DeptEmployee"); + List deptEmployees = query.list(); + DeptEmployee deptEmployee = deptEmployees.get(0); + assertEquals("John Smith", deptEmployee.getName()); + assertEquals("Sales", deptEmployee.getDepartment().getName()); + } + + @Test + public void whenIndividualPropertiesAreSelected_ThenObjectArrayIsReturned() { + Query query = session.createQuery("select m.name, m.department.name from com.baeldung.hibernate.entities.DeptEmployee m"); + List managers = query.list(); + Object[] manager = (Object[]) managers.get(0); + assertEquals("John Smith", manager[0]); + assertEquals("Sales", manager[1]); + } + + @Test + public void whenResultConstructorInSelect_ThenListOfResultIsReturned() { + Query query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) " + + "from DeptEmployee m"); + List results = query.list(); + Result result = results.get(0); + assertEquals("John Smith", result.getEmployeeName()); + assertEquals("Sales", result.getDepartmentName()); + } + + @Test + public void whenResultTransformerOnQuery_ThenListOfResultIsReturned() { + Query query = session.createQuery("select m.name as employeeName, m.department.name as departmentName " + + "from com.baeldung.hibernate.entities.DeptEmployee m"); + query.setResultTransformer(Transformers.aliasToBean(Result.class)); + List results = query.list(); + Result result = results.get(0); + assertEquals("John Smith", result.getEmployeeName()); + assertEquals("Sales", result.getDepartmentName()); + } + + +} diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java new file mode 100644 index 0000000000..7a112200b5 --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -0,0 +1,160 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DynamicMappingIntegrationTest { + + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + + session.createNativeQuery("delete from phone").executeUpdate(); + session.createNativeQuery("delete from employee").executeUpdate(); + + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() { + Employee employee = new Employee(10_000L, 25); + assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L); + + session.save(employee); + session.flush(); + session.clear(); + + employee = session.get(Employee.class, employee.getId()); + assertThat(employee.getTax()).isEqualTo(2_500L); + } + + @Test + public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { + Employee employee = new Employee(); + + session.save(employee); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNotNull(); + + employee.setDeleted(true); + session.flush(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNotNull(); + + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNull(); + + } + + @Test + public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { + Employee employee = new Employee(); + Phone phone1 = new Phone("555-45-67"); + Phone phone2 = new Phone("555-89-01"); + employee.getPhones().add(phone1); + employee.getPhones().add(phone2); + + session.save(phone1); + session.save(phone2); + session.save(employee); + session.flush(); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee.getPhones()).hasSize(2); + + employee.getPhones().iterator().next().setDeleted(true); + session.flush(); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee.getPhones()).hasSize(1); + + List fullPhoneList = session.createQuery("from Phone").getResultList(); + assertThat(fullPhoneList).hasSize(2); + + } + + @Test + public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException { + session.save(new Employee(10_000, 25)); + session.save(new Employee(12_000, 25)); + session.save(new Employee(15_000, 25)); + + session.flush(); + session.clear(); + + session.enableFilter("incomeLevelFilter") + .setParameter("incomeLimit", 11_000); + + List employees = session.createQuery("from Employee").getResultList(); + + assertThat(employees).hasSize(2); + + Employee employee = session.get(Employee.class, 1); + assertThat(employee.getGrossIncome()).isEqualTo(10_000); + + session.disableFilter("incomeLevelFilter"); + employees = session.createQuery("from Employee").getResultList(); + + assertThat(employees).hasSize(3); + + } + + @Test + public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() { + Employee employee = new Employee(); + Phone phone1 = new Phone("555-45-67"); + Phone phone2 = new Phone("555-89-01"); + employee.getPhones().add(phone1); + employee.getPhones().add(phone2); + + EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee); + EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1); + EntityDescription phone2Description = new EntityDescription("Work phone", phone1); + + session.save(phone1); + session.save(phone2); + session.save(employee); + session.save(employeeDescription); + session.save(phone1Description); + session.save(phone2Description); + session.flush(); + session.clear(); + + List descriptions = session.createQuery("from EntityDescription").getResultList(); + + assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue(); + assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue(); + assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue(); + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java new file mode 100644 index 0000000000..0f35dbb8af --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; + +public class InheritanceMappingIntegrationTest { + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenSubclasses_whenQuerySingleTableSuperclass_thenOk() { + Book book = new Book(1, "1984", "George Orwell"); + session.save(book); + Pen pen = new Pen(2, "my pen", "blue"); + session.save(pen); + + assertThat(session.createQuery("from MyProduct") + .getResultList() + .size()).isEqualTo(2); + } + + @Test + public void givenSubclasses_whenQueryMappedSuperclass_thenOk() { + MyEmployee emp = new MyEmployee(1, "john", "baeldung"); + session.save(emp); + + assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Person") + .getResultList() + .size()).isEqualTo(1); + } + + @Test + public void givenSubclasses_whenQueryJoinedTableSuperclass_thenOk() { + Pet pet = new Pet(1, "dog", "lassie"); + session.save(pet); + + assertThat(session.createQuery("from Animal") + .getResultList() + .size()).isEqualTo(1); + } + + @Test + public void givenSubclasses_whenQueryTablePerClassSuperclass_thenOk() { + Car car = new Car(1, "audi", "xyz"); + session.save(car); + + assertThat(session.createQuery("from Vehicle") + .getResultList() + .size()).isEqualTo(1); + } + + @Test + public void givenSubclasses_whenQueryNonMappedInterface_thenOk() { + Bag bag = new Bag(1, "large"); + session.save(bag); + + assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item") + .getResultList() + .size()).isEqualTo(0); + } +} diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java new file mode 100644 index 0000000000..91c41af0fe --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java @@ -0,0 +1,128 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.pojo.TemporalValues; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.*; +import java.util.Calendar; +import java.util.TimeZone; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TemporalValuesUnitTest { + + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().withOptions() + .jdbcTimeZone(TimeZone.getTimeZone("UTC")) + .openSession(); + transaction = session.beginTransaction(); + session.createNativeQuery("delete from temporalvalues").executeUpdate(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15")); + temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14")); + temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15")); + assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14")); + assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + + Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarDate.set(Calendar.YEAR, 2017); + calendarDate.set(Calendar.MONTH, 10); + calendarDate.set(Calendar.DAY_OF_MONTH, 15); + temporalValues.setCalendarDate(calendarDate); + + Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + temporalValues.setCalendarTimestamp(calendarTimestamp); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + + } + + @Test + public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + + temporalValues.setLocalDate(LocalDate.parse("2017-11-15")); + temporalValues.setLocalTime(LocalTime.parse("15:30:18")); + temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00")); + + System.out.println("********"+OffsetTime.parse("08:22:12+01:00").toString()); + temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z")); + temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12")); + temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15")); + assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18")); + //assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00")); + assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z")); + assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12")); + //assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + } + +} diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java new file mode 100644 index 0000000000..398b2290fa --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.lob; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +import org.apache.commons.io.IOUtils; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.lob.model.User; + +public class LobUnitTest { + + private Session session; + + @Before + public void init(){ + try { + session = HibernateSessionUtil.getSessionFactory("hibernate.properties") + .openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close(){ + if(session != null) session.close(); + } + + @Test + public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){ + User user = new User(); + try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) { + // Get Image file from the resource + if(inputStream == null) fail("Unable to get resources"); + user.setId("1"); + user.setName("User"); + user.setPhoto(IOUtils.toByteArray(inputStream)); + + session.persist(user); + } catch (IOException e) { + fail("Unable to read input stream"); + } + + User result = session.find(User.class, "1"); + + assertNotNull("Query result is null", result); + assertEquals("User's name is invalid", user.getName(), result.getName() ); + assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) ); + } +} diff --git a/persistence-modules/hibernate5-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate5-mapping/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;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 diff --git a/persistence-modules/hibernate5-mapping/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate5-mapping/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate5-mapping/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate5-mapping/src/test/resources/profile.png b/persistence-modules/hibernate5-mapping/src/test/resources/profile.png new file mode 100644 index 0000000000000000000000000000000000000000..1cd4e978b96d0f59a6e48692fcb68d1c6c565a20 GIT binary patch literal 1117 zcmV-j1fu(iP)%yyh@V&OYl(_AFwE`D&8)` zPnvkdvc#Z>pRh2kBHk{=qaGfCG;?<;rVe;D+%LyZS~!K}c+|op81YK@rzPHU@Th|m z4Dk`HcojTY;+}_-W%HGqKH@C!LiH8Tp>1lC@aTqoy zBU~QK<}hs@q|M8($ee`o<9#`B3-PL4Y7d9kW#<;n>t}6VNpYCswLrJTtEa_lFwgN$52-_vxvvfJs@B6-OYs%-@M_JTx*UfozG6(Bhs)>w z!pG%vU$b%f++EGa<#Tu1FZ^c#{;G|y5=kM3Y#X^mtSrFA_-o-vX7e_$5-udx(>S4U)i|4)(UJ~zR(vwE+6VTAzoo7wIS|c zh*yt`3wK%<+yX~Z9G1z2GQgf3~qx jc9u$WjpqGof00000NkvXXu0mjfJX<<= literal 0 HcmV?d00001 From 901708063381684ec81918283dcc1f83ab05f7a7 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 11 Mar 2020 18:21:07 +0530 Subject: [PATCH 08/17] JAVA-4 : added new module hibernate5-queries --- .../hibernate5-queries/README.md | 10 ++ .../hibernate5-queries/pom.xml | 82 ++++++++++++++ .../com/baeldung/hibernate/HibernateUtil.java | 73 ++++++++++++ .../UnsupportedTenancyException.java | 8 ++ .../criteriaquery/HibernateUtil.java | 60 ++++++++++ .../hibernate/criteriaquery/Student.java | 58 ++++++++++ .../LocalDateStringJavaDescriptor.java | 51 +++++++++ .../customtypes/LocalDateStringType.java | 34 ++++++ .../hibernate/entities/Department.java | 45 ++++++++ .../hibernate/entities/DeptEmployee.java | 83 ++++++++++++++ .../baeldung/hibernate/findall/FindAll.java | 35 ++++++ .../com/baeldung/hibernate/pojo/Student.java | 51 +++++++++ .../main/resources/META-INF/persistence.xml | 18 +++ .../src/main/resources/init_database.sql | 10 ++ .../src/main/resources/logback.xml | 13 +++ .../hibernate/NamedQueryIntegrationTest.java | 98 ++++++++++++++++ .../TypeSafeCriteriaIntegrationTest.java | 89 +++++++++++++++ .../hibernate/findall/FindAllUnitTest.java | 63 +++++++++++ .../QueryPlanCacheBenchmark.java | 106 ++++++++++++++++++ .../hibernate-customtypes.properties | 14 +++ .../resources/hibernate-namedquery.properties | 9 ++ .../src/test/resources/hibernate.properties | 14 +++ .../src/test/resources/lifecycle-init.sql | 25 +++++ .../src/test/resources/profile.png | Bin 0 -> 1117 bytes 24 files changed, 1049 insertions(+) create mode 100644 persistence-modules/hibernate5-queries/README.md create mode 100644 persistence-modules/hibernate5-queries/pom.xml create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java create mode 100644 persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java create mode 100644 persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml create mode 100644 persistence-modules/hibernate5-queries/src/main/resources/init_database.sql create mode 100644 persistence-modules/hibernate5-queries/src/main/resources/logback.xml create mode 100644 persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java create mode 100644 persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java create mode 100644 persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java create mode 100644 persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java create mode 100644 persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties create mode 100644 persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties create mode 100644 persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties create mode 100644 persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql create mode 100644 persistence-modules/hibernate5-queries/src/test/resources/profile.png diff --git a/persistence-modules/hibernate5-queries/README.md b/persistence-modules/hibernate5-queries/README.md new file mode 100644 index 0000000000..1edf4ded1e --- /dev/null +++ b/persistence-modules/hibernate5-queries/README.md @@ -0,0 +1,10 @@ +## Hibernate 5 + +This module contains articles about Hibernate 5. + +### Relevant articles: + +- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) +- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) \ No newline at end of file diff --git a/persistence-modules/hibernate5-queries/pom.xml b/persistence-modules/hibernate5-queries/pom.xml new file mode 100644 index 0000000000..544d22c0a3 --- /dev/null +++ b/persistence-modules/hibernate5-queries/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + hibernate5-queries + 0.0.1-SNAPSHOT + hibernate5-queries + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + 1.21 + + + diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..58724e690c --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +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; + +import com.baeldung.hibernate.customtypes.LocalDateStringType; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + 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; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.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-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java new file mode 100644 index 0000000000..35cfe55ba6 --- /dev/null +++ b/persistence-modules/hibernate5-queries/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-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java new file mode 100644 index 0000000000..314e7ca557 --- /dev/null +++ b/persistence-modules/hibernate5-queries/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-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java new file mode 100644 index 0000000000..56be9e693f --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.type.LocalDateType; +import org.hibernate.type.descriptor.WrapperOptions; +import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; +import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; +import org.hibernate.type.descriptor.java.MutabilityPlan; + +import java.time.LocalDate; + +public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { + + public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); + + public LocalDateStringJavaDescriptor() { + super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE); + } + + @Override + public String toString(LocalDate value) { + return LocalDateType.FORMATTER.format(value); + } + + @Override + public LocalDate fromString(String string) { + return LocalDate.from(LocalDateType.FORMATTER.parse(string)); + } + + @Override + public X unwrap(LocalDate value, Class type, WrapperOptions options) { + + if (value == null) + return null; + + if (String.class.isAssignableFrom(type)) + return (X) LocalDateType.FORMATTER.format(value); + + throw unknownUnwrap(type); + } + + @Override + public LocalDate wrap(X value, WrapperOptions options) { + if (value == null) + return null; + + if(String.class.isInstance(value)) + return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); + + throw unknownWrap(value.getClass()); + } +} diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java new file mode 100644 index 0000000000..c8d37073e8 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.dialect.Dialect; +import org.hibernate.type.AbstractSingleColumnStandardBasicType; +import org.hibernate.type.DiscriminatorType; +import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; +import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; + +import java.time.LocalDate; + +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { + + public static final LocalDateStringType INSTANCE = new LocalDateStringType(); + + public LocalDateStringType() { + super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + } + + @Override + public String getName() { + return "LocalDateString"; + } + + @Override + public LocalDate stringToObject(String xml) throws Exception { + return fromString(xml); + } + + @Override + public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { + return '\'' + toString(value) + '\''; + } + +} diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java new file mode 100644 index 0000000000..cc0c234df0 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java @@ -0,0 +1,35 @@ +package com.baeldung.hibernate.findall; + +import java.util.List; + +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import org.hibernate.Session; + +import com.baeldung.hibernate.pojo.Student; + +public class FindAll { + + private Session session; + + public FindAll(Session session) { + super(); + this.session = session; + } + + public List findAllWithJpql() { + return session.createQuery("SELECT a FROM Student a", Student.class).getResultList(); + } + + public List findAllWithCriteriaQuery() { + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Student.class); + Root rootEntry = cq.from(Student.class); + CriteriaQuery all = cq.select(rootEntry); + TypedQuery allQuery = session.createQuery(all); + return allQuery.getResultList(); + } +} diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-queries/src/main/resources/init_database.sql b/persistence-modules/hibernate5-queries/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate5-queries/src/main/resources/logback.xml b/persistence-modules/hibernate5-queries/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java new file mode 100644 index 0000000000..cb73fe348c --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java @@ -0,0 +1,98 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.entities.Department; +import com.baeldung.hibernate.entities.DeptEmployee; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.NativeQuery; +import org.hibernate.query.Query; +import org.junit.*; + +import java.io.IOException; + +public class NamedQueryIntegrationTest { + private static Session session; + + private Transaction transaction; + + private Long purchaseDeptId; + + @BeforeClass + public static void setUpClass() throws IOException { + session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession(); + } + + @Before + public void setUp() throws IOException { + transaction = session.beginTransaction(); + session.createNativeQuery("delete from deptemployee").executeUpdate(); + session.createNativeQuery("delete from department").executeUpdate(); + Department salesDepartment = new Department("Sales"); + Department purchaseDepartment = new Department("Purchase"); + DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment); + DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment); + DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment); + session.persist(salesDepartment); + session.persist(purchaseDepartment); + purchaseDeptId = purchaseDepartment.getId(); + session.persist(employee1); + session.persist(employee2); + session.persist(employee3); + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + if(transaction.isActive()) { + transaction.rollback(); + } + } + + @Test + public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() { + Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class); + query.setParameter("employeeNo", "001"); + DeptEmployee result = query.getSingleResult(); + Assert.assertNotNull(result); + Assert.assertEquals("John Wayne", result.getName()); + } + + @Test + public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() { + Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class); + query.setParameter("name", "John Wayne"); + DeptEmployee result = query.getSingleResult(); + Assert.assertNotNull(result); + Assert.assertEquals("001", result.getEmployeeNumber()); + } + + @Test + public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() { + @SuppressWarnings("rawtypes") + NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName"); + query.setParameter("name", "John Wayne"); + DeptEmployee result = (DeptEmployee) query.getSingleResult(); + Assert.assertNotNull(result); + Assert.assertEquals("001", result.getEmployeeNumber()); + } + + @Test + public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() { + Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment"); + spQuery.setParameter("employeeNo", "001"); + Department newDepartment = session.find(Department.class, purchaseDeptId); + spQuery.setParameter("newDepartment", newDepartment); + spQuery.executeUpdate(); + transaction.commit(); + } + + @Test + public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() { + Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation"); + spQuery.setParameter("employeeNumber", "002"); + spQuery.setParameter("newDesignation", "Supervisor"); + spQuery.executeUpdate(); + transaction.commit(); + } +} diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java new file mode 100644 index 0000000000..cedba412d9 --- /dev/null +++ b/persistence-modules/hibernate5-queries/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("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-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java new file mode 100644 index 0000000000..8a1b9e9791 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.hibernate.findall; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Student; + +public class FindAllUnitTest { + + private Session session; + private Transaction transaction; + + private FindAll findAll; + + @Before + public void setUp() throws IOException { + + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + findAll = new FindAll(session); + + session.createNativeQuery("delete from Student").executeUpdate(); + + Student student1 = new Student(); + session.persist(student1); + + Student student2 = new Student(); + session.persist(student2); + + Student student3 = new Student(); + session.persist(student3); + + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenCriteriaQuery_WhenFindAll_ThenGetAllPersons() { + List list = findAll.findAllWithCriteriaQuery(); + assertEquals(3, list.size()); + } + + @Test + public void givenJpql_WhenFindAll_ThenGetAllPersons() { + List list = findAll.findAllWithJpql(); + assertEquals(3, list.size()); + } +} diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java new file mode 100644 index 0000000000..13eae3d877 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java @@ -0,0 +1,106 @@ +package com.baeldung.hibernate.queryplancache; + +import com.baeldung.hibernate.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.jpa.QueryHints; +import org.hibernate.query.Query; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.RunnerException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +public class QueryPlanCacheBenchmark { + + private static final Logger LOGGER = LoggerFactory.getLogger(QueryPlanCacheBenchmark.class); + + @State(Scope.Thread) + public static class QueryPlanCacheBenchMarkState { + @Param({"1", "2", "3"}) + public int planCacheSize; + + public Session session; + + @Setup + public void stateSetup() throws IOException { + LOGGER.info("State - Setup"); + session = initSession(planCacheSize); + LOGGER.info("State - Setup Complete"); + } + + private Session initSession(int planCacheSize) throws IOException { + Properties properties = HibernateUtil.getProperties(); + properties.put("hibernate.query.plan_cache_max_size", planCacheSize); + properties.put("hibernate.query.plan_parameter_metadata_max_size", planCacheSize); + SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties); + return sessionFactory.openSession(); + } + + @TearDown + public void tearDownState() { + LOGGER.info("State - Teardown"); + SessionFactory sessionFactory = session.getSessionFactory(); + session.close(); + sessionFactory.close(); + LOGGER.info("State - Teardown complete"); + } + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + @Fork(1) + @Warmup(iterations = 2) + @Measurement(iterations = 5) + public void givenQueryPlanCacheSize_thenCompileQueries(QueryPlanCacheBenchMarkState state, Blackhole blackhole) { + + Query query1 = findEmployeesByDepartmentNameQuery(state.session); + Query query2 = findEmployeesByDesignationQuery(state.session); + Query query3 = findDepartmentOfAnEmployeeQuery(state.session); + + blackhole.consume(query1); + blackhole.consume(query2); + blackhole.consume(query3); + + } + + private Query findEmployeesByDepartmentNameQuery(Session session) { + return session.createQuery("SELECT e FROM DeptEmployee e " + + "JOIN e.department WHERE e.department.name = :deptName") + .setMaxResults(30) + .setHint(QueryHints.HINT_FETCH_SIZE, 30); + } + + private Query findEmployeesByDesignationQuery(Session session) { + return session.createQuery("SELECT e FROM DeptEmployee e " + + "WHERE e.title = :designation") + .setHint(QueryHints.SPEC_HINT_TIMEOUT, 1000); + } + + private Query findDepartmentOfAnEmployeeQuery(Session session) { + return session.createQuery("SELECT e.department FROM DeptEmployee e " + + "JOIN e.department WHERE e.employeeNumber = :empId"); + + } + + public static void main(String... args) throws IOException, RunnerException { + //main-class to run the benchmark + org.openjdk.jmh.Main.main(args); + } +} diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;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 diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties new file mode 100644 index 0000000000..457f965347 --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' +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 \ No newline at end of file diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties b/persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;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 diff --git a/persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate5-queries/src/test/resources/profile.png b/persistence-modules/hibernate5-queries/src/test/resources/profile.png new file mode 100644 index 0000000000000000000000000000000000000000..1cd4e978b96d0f59a6e48692fcb68d1c6c565a20 GIT binary patch literal 1117 zcmV-j1fu(iP)%yyh@V&OYl(_AFwE`D&8)` zPnvkdvc#Z>pRh2kBHk{=qaGfCG;?<;rVe;D+%LyZS~!K}c+|op81YK@rzPHU@Th|m z4Dk`HcojTY;+}_-W%HGqKH@C!LiH8Tp>1lC@aTqoy zBU~QK<}hs@q|M8($ee`o<9#`B3-PL4Y7d9kW#<;n>t}6VNpYCswLrJTtEa_lFwgN$52-_vxvvfJs@B6-OYs%-@M_JTx*UfozG6(Bhs)>w z!pG%vU$b%f++EGa<#Tu1FZ^c#{;G|y5=kM3Y#X^mtSrFA_-o-vX7e_$5-udx(>S4U)i|4)(UJ~zR(vwE+6VTAzoo7wIS|c zh*yt`3wK%<+yX~Z9G1z2GQgf3~qx jc9u$WjpqGof00000NkvXXu0mjfJX<<= literal 0 HcmV?d00001 From d2d2a890fac064b3fcb48ffcb09fd1ceb0a13b2d Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:37:57 +0530 Subject: [PATCH 09/17] JAVA-4: renamed to hibernate-annotations, moved couple of articles --- .../hibernate5-annotations/README.md | 8 +- .../config/HibernateAnnotationUtil.java | 34 +++++ .../main/HibernateManyisOwningSide.java | 71 +++++++++++ .../HibernateOneToManyAnnotationMain.java | 60 +++++++++ .../main/HibernateOneisOwningSide.java | 67 ++++++++++ .../hibernate/oneToMany/model/Cart.java | 43 +++++++ .../hibernate/oneToMany/model/CartOIO.java | 42 +++++++ .../hibernate/oneToMany/model/Items.java | 50 ++++++++ .../hibernate/oneToMany/model/ItemsOIO.java | 47 +++++++ .../hibernate/wherejointable/Group.java | 56 +++++++++ .../hibernate/wherejointable/User.java | 74 +++++++++++ .../wherejointable/UserGroupRelation.java | 31 +++++ .../wherejointable/UserGroupRole.java | 7 ++ ...neToManyAnnotationMainIntegrationTest.java | 95 ++++++++++++++ ...ibernateWhereJoinTableIntegrationTest.java | 118 ++++++++++++++++++ 15 files changed, 799 insertions(+), 4 deletions(-) create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java create mode 100644 persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java create mode 100644 persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java create mode 100644 persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java diff --git a/persistence-modules/hibernate5-annotations/README.md b/persistence-modules/hibernate5-annotations/README.md index da3c5ad1fd..2813dbdda3 100644 --- a/persistence-modules/hibernate5-annotations/README.md +++ b/persistence-modules/hibernate5-annotations/README.md @@ -1,10 +1,10 @@ -## Hibernate 5 +## Hibernate Annotations -This module contains articles about Hibernate 5. +This module contains articles about Hibernate Annotations. ### Relevant Articles: - [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) -- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) - [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) - [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) - +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) +- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java new file mode 100644 index 0000000000..46e6824f42 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.oneToMany.config; + +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 HibernateAnnotationUtil { + + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { + try { + // Create the SessionFactory from hibernate-annotation.cfg.xml + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); + Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); + SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); + + return sessionFactory; + + } catch (Throwable ex) { + System.err.println("Initial SessionFactory creation failed." + ex); + ex.printStackTrace(); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) + sessionFactory = buildSessionFactory(); + return sessionFactory; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java new file mode 100644 index 0000000000..372fb2fc07 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; +import com.baeldung.hibernate.oneToMany.model.ItemsOIO; + +public class HibernateManyisOwningSide { + public static void main(String[] args) { + + Cart cart = new Cart(); + Cart cart2 = new Cart(); + + Items item1 = new Items(cart); + Items item2 = new Items(cart2); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + + item1 = (Items) session.get(Items.class, new Long(1)); + item2 = (Items) session.get(Items.class, new Long(2)); + tx.commit(); + + + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart() + .getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart() + .getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java new file mode 100644 index 0000000000..2bc5e514f7 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; + +public class HibernateOneToManyAnnotationMain { + + public static void main(String[] args) { + + Cart cart = new Cart(); + + Items item1 = new Items(cart); + Items item2 = new Items(cart); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + System.out.println("Cart ID=" + cart.getId()); + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java new file mode 100644 index 0000000000..0777664dd0 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java @@ -0,0 +1,67 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.CartOIO; +import com.baeldung.hibernate.oneToMany.model.ItemsOIO; + +public class HibernateOneisOwningSide { + public static void main(String[] args) { + + CartOIO cart = new CartOIO(); + CartOIO cart2 = new CartOIO(); + + ItemsOIO item1 = new ItemsOIO(cart); + ItemsOIO item2 = new ItemsOIO(cart2); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1)); + item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2)); + tx.commit(); + + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO() + .getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO() + .getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java new file mode 100644 index 0000000000..b8b991831e --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.oneToMany.model; + +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "CART") +public class Cart { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "cart_id") + private long id; + + + @OneToMany(mappedBy = "cart") + private Set items; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java new file mode 100644 index 0000000000..8a5ed5e7a4 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java @@ -0,0 +1,42 @@ +package com.baeldung.hibernate.oneToMany.model; + +import java.util.Set; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.Table; + + + +@Entity +@Table(name = "CARTOIO") +public class CartOIO { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @OneToMany + @JoinColumn(name = "cart_id") // we need to duplicate the physical information + private Set items; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java new file mode 100644 index 0000000000..f63a4855b5 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.oneToMany.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "ITEMS") +public class Items { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + + @ManyToOne + @JoinColumn(name = "cart_id", nullable = false) + private Cart cart; + + // Hibernate requires no-args constructor + public Items() { + } + + public Items(Cart c) { + this.cart = c; + } + + public Cart getCart() { + return cart; + } + + public void setCart(Cart cart) { + this.cart = cart; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java new file mode 100644 index 0000000000..a3d6a796c5 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.oneToMany.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "ITEMSOIO") +public class ItemsOIO { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @ManyToOne + @JoinColumn(name = "cart_id", insertable = false, updatable = false) + private CartOIO cart; + + // Hibernate requires no-args constructor + public ItemsOIO() { + } + + public ItemsOIO(CartOIO c) { + this.cart = c; + } + + public CartOIO getCartOIO() { + return cart; + } + + public void setCartOIO(CartOIO cart) { + this.cart = cart; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java new file mode 100644 index 0000000000..04684eceac --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java @@ -0,0 +1,56 @@ +package com.baeldung.hibernate.wherejointable; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity(name = "e_group") +public class Group { + + @Id + @GeneratedValue + private Long id; + + private String name; + + @ManyToMany(mappedBy = "groups") + private List users = new ArrayList<>(); + + public Group(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + @Override + public String toString() { + return "Group [name=" + name + "]"; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java new file mode 100644 index 0000000000..7fc077eeb2 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java @@ -0,0 +1,74 @@ +package com.baeldung.hibernate.wherejointable; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +import org.hibernate.annotations.WhereJoinTable; + +@Entity +public class User { + + @Id + @GeneratedValue + private Long id; + + private String name; + + @ManyToMany + @JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) + private List groups = new ArrayList<>(); + + @WhereJoinTable(clause = "role='MODERATOR'") + @ManyToMany + @JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) + private List moderatorGroups = new ArrayList<>(); + + public User(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } + + public void setModeratorGroups(List moderatorGroups) { + this.moderatorGroups = moderatorGroups; + } + + public List getModeratorGroups() { + return moderatorGroups; + } + + @Override + public String toString() { + return "User [name=" + name + "]"; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java new file mode 100644 index 0000000000..00dd19699c --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.wherejointable; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; + +@Entity(name = "r_user_group") +public class UserGroupRelation implements Serializable { + + @Id + @Column(name = "user_id", insertable = false, updatable = false) + private final Long userId; + + @Id + @Column(name = "group_id", insertable = false, updatable = false) + private final Long groupId; + + @Enumerated(EnumType.STRING) + private final UserGroupRole role; + + public UserGroupRelation(Long userId, Long groupId, UserGroupRole role) { + this.userId = userId; + this.groupId = groupId; + this.role = role; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java new file mode 100644 index 0000000000..62d9cb28ea --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java @@ -0,0 +1,7 @@ +package com.baeldung.hibernate.wherejointable; + +public enum UserGroupRole { + + MEMBER, MODERATOR + +} diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java new file mode 100644 index 0000000000..3bc5a6e12a --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java @@ -0,0 +1,95 @@ +package com.baeldung.hibernate.oneToMany.main; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; + +public class HibernateOneToManyAnnotationMainIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + public HibernateOneToManyAnnotationMainIntegrationTest() { + } + + @BeforeClass + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) + .setProperty("hibernate.dialect", H2Dialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") + .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenSession_checkIfDatabaseIsEmpty() { + Cart cart = (Cart) session.get(Cart.class, new Long(1)); + assertNull(cart); + + } + + @Test + public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { + Cart cart = new Cart(); + Set cartItems = new HashSet<>(); + cartItems = cart.getItems(); + Assert.assertNull(cartItems); + Items item1 = new Items(); + item1.setCart(cart); + assertNotNull(item1); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + assertNotNull(itemsSet); + cart.setItems(itemsSet); + assertNotNull(cart); + session.persist(cart); + session.getTransaction().commit(); + session.close(); + + session = sessionFactory.openSession(); + session.beginTransaction(); + cart = (Cart) session.get(Cart.class, new Long(1)); + assertNotNull(cart); + } + + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java new file mode 100644 index 0000000000..93783216ce --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java @@ -0,0 +1,118 @@ +package com.baeldung.hibernate.wherejointable; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class HibernateWhereJoinTableIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + /** + * Test data + */ + private User user1; + private User user2; + private User user3; + private Group group1; + private Group group2; + + @BeforeClass + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(User.class) + .addAnnotatedClass(Group.class) + .addAnnotatedClass(UserGroupRelation.class) + .setProperty("hibernate.dialect", H2Dialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") + .setProperty("hibernate.connection.username", "sa") + .setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()) + .build(); + + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + + user1 = new User("user1"); + user2 = new User("user2"); + user3 = new User("user3"); + + group1 = new Group("group1"); + group2 = new Group("group2"); + + session.save(group1); + session.save(group2); + + session.save(user1); + session.save(user2); + session.save(user3); + + saveRelation(user1, group1, UserGroupRole.MODERATOR); + saveRelation(user2, group1, UserGroupRole.MODERATOR); + saveRelation(user3, group1, UserGroupRole.MEMBER); + + saveRelation(user1, group2, UserGroupRole.MEMBER); + saveRelation(user2, group2, UserGroupRole.MODERATOR); + } + + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + + @Test + public void givenUser1_getGroups_returnsAllGroups() { + List groups = user1.getGroups(); + assertEquals(2, groups.size()); + + assertTrue(groups.contains(group1)); + assertTrue(groups.contains(group2)); + } + + @Test + public void givenUser1_getModeratorGroups_returnsOnlyModeratorGroups() { + List groups = user1.getModeratorGroups(); + assertEquals(1, groups.size()); + + assertTrue(groups.contains(group1)); + } + + private void saveRelation(User user, Group group, UserGroupRole role) { + UserGroupRelation relation = new UserGroupRelation(user.getId(), group.getId(), role); + + session.save(relation); + session.flush(); + session.refresh(user); + session.refresh(group); + } + +} From 12a7e6fdf92f47a451fe64a66fc5bd22176fdae6 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:48:26 +0530 Subject: [PATCH 10/17] JAVA-4: Renamed hibernate5-annotations to hibernate-annotations --- .../README.md | 0 .../pom.xml | 4 ++-- .../java/com/baeldung/hibernate/HibernateUtil.java | 0 .../hibernate/UnsupportedTenancyException.java | 0 .../com/baeldung/hibernate/customtypes/Address.java | 0 .../baeldung/hibernate/customtypes/AddressType.java | 0 .../customtypes/LocalDateStringJavaDescriptor.java | 0 .../hibernate/customtypes/LocalDateStringType.java | 0 .../hibernate/customtypes/OfficeEmployee.java | 0 .../baeldung/hibernate/customtypes/PhoneNumber.java | 0 .../hibernate/customtypes/PhoneNumberType.java | 0 .../com/baeldung/hibernate/customtypes/Salary.java | 0 .../customtypes/SalaryCurrencyConvertor.java | 0 .../baeldung/hibernate/customtypes/SalaryType.java | 0 .../com/baeldung/hibernate/joincolumn/Email.java | 0 .../com/baeldung/hibernate/joincolumn/Office.java | 0 .../hibernate/joincolumn/OfficeAddress.java | 0 .../hibernate/joincolumn/OfficialEmployee.java | 0 .../oneToMany/config/HibernateAnnotationUtil.java | 0 .../oneToMany/main/HibernateManyisOwningSide.java | 0 .../main/HibernateOneToManyAnnotationMain.java | 0 .../oneToMany/main/HibernateOneisOwningSide.java | 0 .../baeldung/hibernate/oneToMany/model/Cart.java | 0 .../baeldung/hibernate/oneToMany/model/CartOIO.java | 0 .../baeldung/hibernate/oneToMany/model/Items.java | 0 .../hibernate/oneToMany/model/ItemsOIO.java | 0 .../java/com/baeldung/hibernate/pojo/Phone.java | 0 .../baeldung/hibernate/wherejointable/Group.java | 0 .../com/baeldung/hibernate/wherejointable/User.java | 0 .../hibernate/wherejointable/UserGroupRelation.java | 0 .../hibernate/wherejointable/UserGroupRole.java | 0 .../src/main/resources/META-INF/persistence.xml | 0 .../src/main/resources/logback.xml | 0 .../customtypes/HibernateCustomTypesManualTest.java | 0 .../joincolumn/JoinColumnIntegrationTest.java | 0 ...rnateOneToManyAnnotationMainIntegrationTest.java | 0 .../HibernateWhereJoinTableIntegrationTest.java | 0 .../src/test/resources/hibernate-spatial.properties | 0 .../src/test/resources/log4j.xml | 0 .../src/test/resources/log4j2.xml | 0 .../src/test/resources/logback.xml | 0 .../src/test/resources/profile.png | Bin 42 files changed, 2 insertions(+), 2 deletions(-) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/README.md (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/pom.xml (96%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/HibernateUtil.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/Address.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/Salary.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/joincolumn/Email.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/joincolumn/Office.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/pojo/Phone.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/wherejointable/Group.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/wherejointable/User.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/resources/META-INF/persistence.xml (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/main/resources/logback.xml (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/resources/hibernate-spatial.properties (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/resources/log4j.xml (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/resources/log4j2.xml (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/resources/logback.xml (100%) rename persistence-modules/{hibernate5-annotations => hibernate-annotations}/src/test/resources/profile.png (100%) diff --git a/persistence-modules/hibernate5-annotations/README.md b/persistence-modules/hibernate-annotations/README.md similarity index 100% rename from persistence-modules/hibernate5-annotations/README.md rename to persistence-modules/hibernate-annotations/README.md diff --git a/persistence-modules/hibernate5-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml similarity index 96% rename from persistence-modules/hibernate5-annotations/pom.xml rename to persistence-modules/hibernate-annotations/pom.xml index ab242333fe..5367921f31 100644 --- a/persistence-modules/hibernate5-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - hibernate5-annotations + hibernate-annotations 0.1-SNAPSHOT - hibernate5-annotations + hibernate-annotations jar Hibernate tutorial illustrating the use of named parameters diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java diff --git a/persistence-modules/hibernate5-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/resources/META-INF/persistence.xml rename to persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml diff --git a/persistence-modules/hibernate5-annotations/src/main/resources/logback.xml b/persistence-modules/hibernate-annotations/src/main/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-annotations/src/main/resources/logback.xml rename to persistence-modules/hibernate-annotations/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/resources/hibernate-spatial.properties rename to persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/resources/log4j.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j.xml diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/log4j2.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/resources/log4j2.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/logback.xml b/persistence-modules/hibernate-annotations/src/test/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/resources/logback.xml rename to persistence-modules/hibernate-annotations/src/test/resources/logback.xml diff --git a/persistence-modules/hibernate5-annotations/src/test/resources/profile.png b/persistence-modules/hibernate-annotations/src/test/resources/profile.png similarity index 100% rename from persistence-modules/hibernate5-annotations/src/test/resources/profile.png rename to persistence-modules/hibernate-annotations/src/test/resources/profile.png From 5f8123f80493e8c85a09db24075146bd6c8f1715 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:50:17 +0530 Subject: [PATCH 11/17] JAVA-4: Renamed hibernate5-enterprise to hibernate-enterprise --- .../README.md | 5 ++--- .../pom.xml | 4 ++-- .../java/com/baeldung/hibernate/HibernateUtil.java | 0 .../hibernate/UnsupportedTenancyException.java | 0 .../hibernate/exception/EntityWithNoId.java | 0 .../baeldung/hibernate/exception/HibernateUtil.java | 0 .../com/baeldung/hibernate/exception/Product.java | 0 .../com/baeldung/hibernate/logging/Employee.java | 0 .../com/baeldung/hibernate/pojo/PointEntity.java | 0 .../com/baeldung/hibernate/pojo/PolygonEntity.java | 0 .../java/com/baeldung/hibernate/pojo/Student.java | 0 .../com/baeldung/hibernateparameters/Event.java | 0 .../src/main/resources/META-INF/persistence.xml | 0 .../com/baeldung/hibernateparameters/Event.hbm.xml | 0 .../src/main/resources/hibernate-logging.cfg.xml | 0 .../src/main/resources/hibernate.cfg.xml | 0 .../src/main/resources/init_database.sql | 0 .../src/main/resources/logback.xml | 0 .../hibernate/HibernateSpatialIntegrationTest.java | 0 .../AggregateFunctionsIntegrationTest.java | 0 .../exception/HibernateExceptionUnitTest.java | 0 .../logging/HibernateLoggingIntegrationTest.java | 0 .../com/baeldung/hibernate/multitenancy/Car.java | 0 .../multitenancy/MultitenancyIntegrationTest.java | 0 ...DatabaseApproachMultitenancyIntegrationTest.java | 0 .../database/MapMultiTenantConnectionProvider.java | 0 .../multitenancy/database/TenantIdNames.java | 0 .../SchemaApproachMultitenancyIntegrationTest.java | 0 .../schema/SchemaMultiTenantConnectionProvider.java | 0 .../multitenancy/schema/TenantIdNames.java | 0 .../hibernateparameters/NamedParameterUnitTest.java | 0 .../hibernate-database-multitenancy.properties | 0 .../resources/hibernate-database-mydb1.properties | 0 .../resources/hibernate-database-mydb2.properties | 0 .../test/resources/hibernate-exception.properties | 0 .../hibernate-schema-multitenancy.properties | 0 .../src/test/resources/hibernate-spatial.properties | 0 .../src/test/resources/hibernate.properties | 0 .../src/test/resources/lifecycle-init.sql | 0 .../src/test/resources/profile.png | Bin 40 files changed, 4 insertions(+), 5 deletions(-) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/README.md (81%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/pom.xml (96%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/HibernateUtil.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/exception/Product.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/logging/Employee.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernate/pojo/Student.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/java/com/baeldung/hibernateparameters/Event.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/resources/META-INF/persistence.xml (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/resources/hibernate-logging.cfg.xml (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/resources/hibernate.cfg.xml (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/resources/init_database.sql (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/main/resources/logback.xml (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/Car.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/hibernate-database-multitenancy.properties (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/hibernate-database-mydb1.properties (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/hibernate-database-mydb2.properties (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/hibernate-exception.properties (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/hibernate-schema-multitenancy.properties (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/hibernate-spatial.properties (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/hibernate.properties (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/lifecycle-init.sql (100%) rename persistence-modules/{hibernate5-enterprise => hibernate-enterprise}/src/test/resources/profile.png (100%) diff --git a/persistence-modules/hibernate5-enterprise/README.md b/persistence-modules/hibernate-enterprise/README.md similarity index 81% rename from persistence-modules/hibernate5-enterprise/README.md rename to persistence-modules/hibernate-enterprise/README.md index 994d8f062a..c48092e6a2 100644 --- a/persistence-modules/hibernate5-enterprise/README.md +++ b/persistence-modules/hibernate-enterprise/README.md @@ -1,6 +1,6 @@ -## Hibernate 5 +## Hibernate Enterprise -This module contains articles about Hibernate 5. +This module contains articles about Hibernate. ### Relevant articles: @@ -9,5 +9,4 @@ This module contains articles about Hibernate 5. - [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) - [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) - [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) -- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) - [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) \ No newline at end of file diff --git a/persistence-modules/hibernate5-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml similarity index 96% rename from persistence-modules/hibernate5-enterprise/pom.xml rename to persistence-modules/hibernate-enterprise/pom.xml index f12bb7e081..060cb4c904 100644 --- a/persistence-modules/hibernate5-enterprise/pom.xml +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -3,9 +3,9 @@ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - hibernate5-enterprise + hibernate-enterprise 0.0.1-SNAPSHOT - hibernate5-enterprise + hibernate-enterprise com.baeldung diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/resources/META-INF/persistence.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml b/persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate-logging.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/resources/hibernate-logging.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/hibernate.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/resources/hibernate.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/init_database.sql b/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/resources/init_database.sql rename to persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql diff --git a/persistence-modules/hibernate5-enterprise/src/main/resources/logback.xml b/persistence-modules/hibernate-enterprise/src/main/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/main/resources/logback.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb1.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb1.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb2.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-database-mydb2.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-exception.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-schema-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-schema-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/hibernate-spatial.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/hibernate.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/hibernate.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/lifecycle-init.sql rename to persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql diff --git a/persistence-modules/hibernate5-enterprise/src/test/resources/profile.png b/persistence-modules/hibernate-enterprise/src/test/resources/profile.png similarity index 100% rename from persistence-modules/hibernate5-enterprise/src/test/resources/profile.png rename to persistence-modules/hibernate-enterprise/src/test/resources/profile.png From 376d0a6ff6389def371ecef2fde4aefc8aa821eb Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:51:47 +0530 Subject: [PATCH 12/17] JAVA-4: Renamed hibernate5-jpa to hibernate-jpa --- .../{hibernate5-jpa => hibernate-jpa}/README.md | 5 ++--- .../{hibernate5-jpa => hibernate-jpa}/pom.xml | 4 ++-- .../java/com/baeldung/hibernate/HibernateUtil.java | 0 .../hibernate/UnsupportedTenancyException.java | 0 .../hibernate/converters/PersonNameConverter.java | 0 .../com/baeldung/hibernate/entities/Department.java | 0 .../baeldung/hibernate/entities/DeptEmployee.java | 0 .../jpabootstrap/application/Application.java | 0 .../config/HibernatePersistenceUnitInfo.java | 0 .../config/JpaEntityManagerFactory.java | 0 .../hibernate/jpabootstrap/entities/User.java | 0 .../service/EmployeeSearchService.java | 0 .../service/EmployeeSearchServiceImpl.java | 0 .../baeldung/hibernate/onetoone/HibernateUtil.java | 0 .../com/baeldung/hibernate/onetoone/Strategy.java | 0 .../hibernate/onetoone/foreignkeybased/Address.java | 0 .../hibernate/onetoone/foreignkeybased/User.java | 0 .../hibernate/onetoone/jointablebased/Employee.java | 0 .../onetoone/jointablebased/WorkStation.java | 0 .../hibernate/onetoone/sharedkeybased/Address.java | 0 .../hibernate/onetoone/sharedkeybased/User.java | 0 .../optimisticlocking/OptimisticLockingCourse.java | 0 .../optimisticlocking/OptimisticLockingStudent.java | 0 .../hibernate/pessimisticlocking/Address.java | 0 .../hibernate/pessimisticlocking/Customer.java | 0 .../hibernate/pessimisticlocking/Individual.java | 0 .../PessimisticLockingCourse.java | 0 .../PessimisticLockingEmployee.java | 0 .../PessimisticLockingStudent.java | 0 .../java/com/baeldung/hibernate/pojo/Movie.java | 0 .../java/com/baeldung/hibernate/pojo/Person.java | 0 .../com/baeldung/hibernate/pojo/PersonName.java | 0 .../main/java/com/baeldung/hibernate/pojo/Post.java | 0 .../java/com/baeldung/hibernate/pojo/Student.java | 0 .../baeldung/hibernate/transaction/PostService.java | 0 .../PersistenceContextDemoApplication.java | 0 .../baeldung/persistencecontext/entity/User.java | 0 .../ExtendedPersistenceContextUserService.java | 0 .../TransctionPersistenceContextUserService.java | 0 .../src/main/resources/META-INF/persistence.xml | 0 .../src/main/resources/init_database.sql | 0 .../src/main/resources/logback.xml | 0 .../converter/PersonNameConverterUnitTest.java | 0 .../EmployeeSearchServiceIntegrationTest.java | 0 ...ateOneToOneAnnotationFKBasedIntegrationTest.java | 0 ...ateOneToOneAnnotationJTBasedIntegrationTest.java | 0 ...teOneToOneAnnotationSPKBasedIntegrationTest.java | 0 .../OptimisticLockingIntegrationTest.java | 0 .../BasicPessimisticLockingIntegrationTest.java | 0 .../PessimisticLockScopesIntegrationTest.java | 0 .../transaction/TransactionIntegrationTest.java | 0 .../PersistenceContextIntegrationTest.java | 0 .../test/resources/hibernate-namedquery.properties | 0 .../hibernate-pessimistic-locking.properties | 0 .../src/test/resources/hibernate.properties | 0 .../src/test/resources/profile.png | Bin 56 files changed, 4 insertions(+), 5 deletions(-) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/README.md (84%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/pom.xml (97%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/HibernateUtil.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/entities/Department.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pojo/Movie.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pojo/Person.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pojo/PersonName.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pojo/Post.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/pojo/Student.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/hibernate/transaction/PostService.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/persistencecontext/entity/User.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/resources/META-INF/persistence.xml (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/resources/init_database.sql (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/main/resources/logback.xml (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/resources/hibernate-namedquery.properties (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/resources/hibernate-pessimistic-locking.properties (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/resources/hibernate.properties (100%) rename persistence-modules/{hibernate5-jpa => hibernate-jpa}/src/test/resources/profile.png (100%) diff --git a/persistence-modules/hibernate5-jpa/README.md b/persistence-modules/hibernate-jpa/README.md similarity index 84% rename from persistence-modules/hibernate5-jpa/README.md rename to persistence-modules/hibernate-jpa/README.md index bffba85d54..fb1d46cf9b 100644 --- a/persistence-modules/hibernate5-jpa/README.md +++ b/persistence-modules/hibernate-jpa/README.md @@ -1,6 +1,6 @@ -## Hibernate 5 +## Hibernate JPA -This module contains articles about Hibernate 5. +This module contains articles about Hibernate JPA. ### Relevant articles: @@ -12,5 +12,4 @@ This module contains articles about Hibernate 5. - [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) - [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) -- [FetchMode in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-fetchmode) - [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) diff --git a/persistence-modules/hibernate5-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml similarity index 97% rename from persistence-modules/hibernate5-jpa/pom.xml rename to persistence-modules/hibernate-jpa/pom.xml index b181fff36b..67f40d5017 100644 --- a/persistence-modules/hibernate5-jpa/pom.xml +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -3,9 +3,9 @@ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - hibernate5-jpa + hibernate-jpa 0.0.1-SNAPSHOT - hibernate5-jpa + hibernate-jpa com.baeldung diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java diff --git a/persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java diff --git a/persistence-modules/hibernate5-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/resources/META-INF/persistence.xml rename to persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml diff --git a/persistence-modules/hibernate5-jpa/src/main/resources/init_database.sql b/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/resources/init_database.sql rename to persistence-modules/hibernate-jpa/src/main/resources/init_database.sql diff --git a/persistence-modules/hibernate5-jpa/src/main/resources/logback.xml b/persistence-modules/hibernate-jpa/src/main/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-jpa/src/main/resources/logback.xml rename to persistence-modules/hibernate-jpa/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/resources/hibernate-namedquery.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/resources/hibernate-pessimistic-locking.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/hibernate.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/resources/hibernate.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties diff --git a/persistence-modules/hibernate5-jpa/src/test/resources/profile.png b/persistence-modules/hibernate-jpa/src/test/resources/profile.png similarity index 100% rename from persistence-modules/hibernate5-jpa/src/test/resources/profile.png rename to persistence-modules/hibernate-jpa/src/test/resources/profile.png From 729d35140e65bcf949bccb4faa37a76c20f8bd89 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:52:48 +0530 Subject: [PATCH 13/17] JAVA-4: Renamed hibernate5-queries to hibernate-queries --- .../README.md | 4 ++-- .../pom.xml | 4 ++-- .../java/com/baeldung/hibernate/HibernateUtil.java | 0 .../hibernate/UnsupportedTenancyException.java | 0 .../hibernate/criteriaquery/HibernateUtil.java | 0 .../baeldung/hibernate/criteriaquery/Student.java | 0 .../customtypes/LocalDateStringJavaDescriptor.java | 0 .../hibernate/customtypes/LocalDateStringType.java | 0 .../com/baeldung/hibernate/entities/Department.java | 0 .../baeldung/hibernate/entities/DeptEmployee.java | 0 .../com/baeldung/hibernate/findall/FindAll.java | 0 .../java/com/baeldung/hibernate/pojo/Student.java | 0 .../src/main/resources/META-INF/persistence.xml | 0 .../src/main/resources/init_database.sql | 0 .../src/main/resources/logback.xml | 0 .../hibernate/NamedQueryIntegrationTest.java | 0 .../TypeSafeCriteriaIntegrationTest.java | 0 .../baeldung/hibernate/findall/FindAllUnitTest.java | 0 .../queryplancache/QueryPlanCacheBenchmark.java | 0 .../test/resources/hibernate-customtypes.properties | 0 .../test/resources/hibernate-namedquery.properties | 0 .../src/test/resources/hibernate.properties | 0 .../src/test/resources/lifecycle-init.sql | 0 .../src/test/resources/profile.png | Bin 24 files changed, 4 insertions(+), 4 deletions(-) rename persistence-modules/{hibernate5-queries => hibernate-queries}/README.md (81%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/pom.xml (97%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/HibernateUtil.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/entities/Department.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/findall/FindAll.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/java/com/baeldung/hibernate/pojo/Student.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/resources/META-INF/persistence.xml (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/resources/init_database.sql (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/main/resources/logback.xml (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/resources/hibernate-customtypes.properties (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/resources/hibernate-namedquery.properties (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/resources/hibernate.properties (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/resources/lifecycle-init.sql (100%) rename persistence-modules/{hibernate5-queries => hibernate-queries}/src/test/resources/profile.png (100%) diff --git a/persistence-modules/hibernate5-queries/README.md b/persistence-modules/hibernate-queries/README.md similarity index 81% rename from persistence-modules/hibernate5-queries/README.md rename to persistence-modules/hibernate-queries/README.md index 1edf4ded1e..61d94e32de 100644 --- a/persistence-modules/hibernate5-queries/README.md +++ b/persistence-modules/hibernate-queries/README.md @@ -1,6 +1,6 @@ -## Hibernate 5 +## Hibernate Queries -This module contains articles about Hibernate 5. +This module contains articles about use of Queries in Hibernate. ### Relevant articles: diff --git a/persistence-modules/hibernate5-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml similarity index 97% rename from persistence-modules/hibernate5-queries/pom.xml rename to persistence-modules/hibernate-queries/pom.xml index 544d22c0a3..a439ded9df 100644 --- a/persistence-modules/hibernate5-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -3,9 +3,9 @@ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - hibernate5-queries + hibernate-queries 0.0.1-SNAPSHOT - hibernate5-queries + hibernate-queries com.baeldung diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java diff --git a/persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml rename to persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml diff --git a/persistence-modules/hibernate5-queries/src/main/resources/init_database.sql b/persistence-modules/hibernate-queries/src/main/resources/init_database.sql similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/resources/init_database.sql rename to persistence-modules/hibernate-queries/src/main/resources/init_database.sql diff --git a/persistence-modules/hibernate5-queries/src/main/resources/logback.xml b/persistence-modules/hibernate-queries/src/main/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-queries/src/main/resources/logback.xml rename to persistence-modules/hibernate-queries/src/main/resources/logback.xml diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties rename to persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties rename to persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties rename to persistence-modules/hibernate-queries/src/test/resources/hibernate.properties diff --git a/persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql rename to persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql diff --git a/persistence-modules/hibernate5-queries/src/test/resources/profile.png b/persistence-modules/hibernate-queries/src/test/resources/profile.png similarity index 100% rename from persistence-modules/hibernate5-queries/src/test/resources/profile.png rename to persistence-modules/hibernate-queries/src/test/resources/profile.png From bf60206022d577f030e939dae58e1aece5b45a8a Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:53:28 +0530 Subject: [PATCH 14/17] JAVA-4: Removed hibernate5-mapping; merged into to hibernate-mapping --- .../hibernate-mapping/README.md | 8 +- persistence-modules/hibernate-mapping/pom.xml | 13 ++ .../com/baeldung/hibernate/HibernateUtil.java | 72 +++++++++-- .../hibernate/entities/Department.java | 0 .../hibernate/entities/DeptEmployee.java | 0 .../hibernate/lob/HibernateSessionUtil.java | 0 .../baeldung/hibernate/lob/model/User.java | 0 .../config/HibernateAnnotationUtil.java | 34 ----- .../main/HibernateManyisOwningSide.java | 71 ----------- .../HibernateOneToManyAnnotationMain.java | 60 --------- .../main/HibernateOneisOwningSide.java | 67 ---------- .../hibernate/oneToMany/model/Cart.java | 43 ------- .../hibernate/oneToMany/model/CartOIO.java | 42 ------- .../hibernate/oneToMany/model/Items.java | 50 -------- .../hibernate/oneToMany/model/ItemsOIO.java | 47 ------- .../com/baeldung/hibernate/pojo/Employee.java | 0 .../hibernate/pojo/EntityDescription.java | 0 .../com/baeldung/hibernate/pojo/Phone.java | 0 .../com/baeldung/hibernate/pojo/Result.java | 0 .../hibernate/pojo/TemporalValues.java | 0 .../hibernate/pojo/generator/MyGenerator.java | 0 .../hibernate/pojo/inheritance/Animal.java | 0 .../hibernate/pojo/inheritance/Bag.java | 0 .../hibernate/pojo/inheritance/Book.java | 0 .../hibernate/pojo/inheritance/Car.java | 0 .../hibernate/pojo/inheritance/Item.java | 0 .../pojo/inheritance/MyEmployee.java | 0 .../hibernate/pojo/inheritance/MyProduct.java | 0 .../hibernate/pojo/inheritance/Pen.java | 0 .../hibernate/pojo/inheritance/Person.java | 0 .../hibernate/pojo/inheritance/Pet.java | 0 .../hibernate/pojo/inheritance/Vehicle.java | 0 .../baeldung/hibernate/pojo/package-info.java | 0 .../hibernate/wherejointable/Group.java | 56 --------- .../hibernate/wherejointable/User.java | 74 ----------- .../wherejointable/UserGroupRelation.java | 31 ----- .../wherejointable/UserGroupRole.java | 7 -- .../hibernate/CustomClassIntegrationTest.java | 0 .../DynamicMappingIntegrationTest.java | 0 .../InheritanceMappingIntegrationTest.java | 0 .../hibernate/TemporalValuesUnitTest.java | 0 .../baeldung/hibernate/lob/LobUnitTest.java | 0 ...neToManyAnnotationMainIntegrationTest.java | 95 -------------- ...ibernateWhereJoinTableIntegrationTest.java | 118 ------------------ .../src/test/resources/hibernate.properties | 0 .../src/test/resources/lifecycle-init.sql | 0 .../src/test/resources/profile.png | Bin 47 files changed, 83 insertions(+), 805 deletions(-) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/entities/Department.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/lob/model/User.java (100%) delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/Employee.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/Phone.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/Result.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/main/java/com/baeldung/hibernate/pojo/package-info.java (100%) delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java delete mode 100644 persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java (100%) delete mode 100644 persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java delete mode 100644 persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/resources/hibernate.properties (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/resources/lifecycle-init.sql (100%) rename persistence-modules/{hibernate5-mapping => hibernate-mapping}/src/test/resources/profile.png (100%) diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 5bbdeecbea..5ba73f35f3 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -7,5 +7,9 @@ This module contains articles about Object-relational Mapping (ORM) with Hiberna - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) - [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) -- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) -- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) +- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) +- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) +- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) +- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) +- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) +- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index ac7952fa2b..c7318ee425 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -51,6 +51,17 @@ ${moneta.version} pom + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + commons-io + commons-io + ${commons-io.version} + + @@ -60,6 +71,8 @@ 3.0.1-b11 1.0.3 1.3 + 3.9 + 2.6 diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 7de13db8d3..fbd8bd487b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,21 +1,48 @@ package com.baeldung.hibernate; -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 { +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; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; private HibernateUtil() { } + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(""); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + if(propertyFileName.equals("")) propertyFileName = null; + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + public static SessionFactory getSessionFactory(Strategy strategy) { return buildSessionFactory(strategy); } @@ -40,6 +67,35 @@ public class HibernateUtil { } } + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getProperties(); @@ -51,7 +107,7 @@ public class HibernateUtil { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() - .getResource("hibernate.properties"); + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java deleted file mode 100644 index 46e6824f42..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.hibernate.oneToMany.config; - -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 HibernateAnnotationUtil { - - private static SessionFactory sessionFactory; - - private static SessionFactory buildSessionFactory() { - try { - // Create the SessionFactory from hibernate-annotation.cfg.xml - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); - Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); - SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); - - return sessionFactory; - - } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - ex.printStackTrace(); - throw new ExceptionInInitializerError(ex); - } - } - - public static SessionFactory getSessionFactory() { - if (sessionFactory == null) - sessionFactory = buildSessionFactory(); - return sessionFactory; - } -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java deleted file mode 100644 index 372fb2fc07..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.hibernate.oneToMany.main; - -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; -import com.baeldung.hibernate.oneToMany.model.ItemsOIO; - -public class HibernateManyisOwningSide { - public static void main(String[] args) { - - Cart cart = new Cart(); - Cart cart2 = new Cart(); - - Items item1 = new Items(cart); - Items item2 = new Items(cart2); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - itemsSet.add(item2); - - cart.setItems(itemsSet); - - - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); - // start transaction - tx = session.beginTransaction(); - // Save the Model object - session.save(cart); - session.save(cart2); - session.save(item1); - session.save(item2); - // Commit transaction - tx.commit(); - session = sessionFactory.getCurrentSession(); - tx = session.beginTransaction(); - - item1 = (Items) session.get(Items.class, new Long(1)); - item2 = (Items) session.get(Items.class, new Long(2)); - tx.commit(); - - - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart() - .getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart() - .getId()); - - } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); - } finally { - if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java deleted file mode 100644 index 2bc5e514f7..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.hibernate.oneToMany.main; - -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; - -public class HibernateOneToManyAnnotationMain { - - public static void main(String[] args) { - - Cart cart = new Cart(); - - Items item1 = new Items(cart); - Items item2 = new Items(cart); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - itemsSet.add(item2); - - cart.setItems(itemsSet); - - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); - // start transaction - tx = session.beginTransaction(); - // Save the Model object - session.save(cart); - session.save(item1); - session.save(item2); - // Commit transaction - tx.commit(); - System.out.println("Cart ID=" + cart.getId()); - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); - - } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); - } finally { - if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } - -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java deleted file mode 100644 index 0777664dd0..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.hibernate.oneToMany.main; - -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; -import com.baeldung.hibernate.oneToMany.model.CartOIO; -import com.baeldung.hibernate.oneToMany.model.ItemsOIO; - -public class HibernateOneisOwningSide { - public static void main(String[] args) { - - CartOIO cart = new CartOIO(); - CartOIO cart2 = new CartOIO(); - - ItemsOIO item1 = new ItemsOIO(cart); - ItemsOIO item2 = new ItemsOIO(cart2); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - itemsSet.add(item2); - - cart.setItems(itemsSet); - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); - // start transaction - tx = session.beginTransaction(); - // Save the Model object - session.save(cart); - session.save(cart2); - session.save(item1); - session.save(item2); - // Commit transaction - tx.commit(); - - session = sessionFactory.getCurrentSession(); - tx = session.beginTransaction(); - item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1)); - item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2)); - tx.commit(); - - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO() - .getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO() - .getId()); - - } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); - } finally { - if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java deleted file mode 100644 index b8b991831e..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.hibernate.oneToMany.model; - -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; - -@Entity -@Table(name = "CART") -public class Cart { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "cart_id") - private long id; - - - @OneToMany(mappedBy = "cart") - private Set items; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - - public Set getItems() { - return items; - } - - public void setItems(Set items) { - this.items = items; - } - -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java deleted file mode 100644 index 8a5ed5e7a4..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.hibernate.oneToMany.model; - -import java.util.Set; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.Table; - - - -@Entity -@Table(name = "CARTOIO") -public class CartOIO { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - @OneToMany - @JoinColumn(name = "cart_id") // we need to duplicate the physical information - private Set items; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public Set getItems() { - return items; - } - - public void setItems(Set items) { - this.items = items; - } - -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java deleted file mode 100644 index f63a4855b5..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.hibernate.oneToMany.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "ITEMS") -public class Items { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - - @ManyToOne - @JoinColumn(name = "cart_id", nullable = false) - private Cart cart; - - // Hibernate requires no-args constructor - public Items() { - } - - public Items(Cart c) { - this.cart = c; - } - - public Cart getCart() { - return cart; - } - - public void setCart(Cart cart) { - this.cart = cart; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java deleted file mode 100644 index a3d6a796c5..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.hibernate.oneToMany.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "ITEMSOIO") -public class ItemsOIO { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - @ManyToOne - @JoinColumn(name = "cart_id", insertable = false, updatable = false) - private CartOIO cart; - - // Hibernate requires no-args constructor - public ItemsOIO() { - } - - public ItemsOIO(CartOIO c) { - this.cart = c; - } - - public CartOIO getCartOIO() { - return cart; - } - - public void setCartOIO(CartOIO cart) { - this.cart = cart; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - -} diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java diff --git a/persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java deleted file mode 100644 index 04684eceac..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.hibernate.wherejointable; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -@Entity(name = "e_group") -public class Group { - - @Id - @GeneratedValue - private Long id; - - private String name; - - @ManyToMany(mappedBy = "groups") - private List users = new ArrayList<>(); - - public Group(String name) { - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getUsers() { - return users; - } - - public void setUsers(List users) { - this.users = users; - } - - @Override - public String toString() { - return "Group [name=" + name + "]"; - } - -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java deleted file mode 100644 index 7fc077eeb2..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.hibernate.wherejointable; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; - -import org.hibernate.annotations.WhereJoinTable; - -@Entity -public class User { - - @Id - @GeneratedValue - private Long id; - - private String name; - - @ManyToMany - @JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) - private List groups = new ArrayList<>(); - - @WhereJoinTable(clause = "role='MODERATOR'") - @ManyToMany - @JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) - private List moderatorGroups = new ArrayList<>(); - - public User(String name) { - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getGroups() { - return groups; - } - - public void setGroups(List groups) { - this.groups = groups; - } - - public void setModeratorGroups(List moderatorGroups) { - this.moderatorGroups = moderatorGroups; - } - - public List getModeratorGroups() { - return moderatorGroups; - } - - @Override - public String toString() { - return "User [name=" + name + "]"; - } - -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java deleted file mode 100644 index 00dd19699c..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.hibernate.wherejointable; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; - -@Entity(name = "r_user_group") -public class UserGroupRelation implements Serializable { - - @Id - @Column(name = "user_id", insertable = false, updatable = false) - private final Long userId; - - @Id - @Column(name = "group_id", insertable = false, updatable = false) - private final Long groupId; - - @Enumerated(EnumType.STRING) - private final UserGroupRole role; - - public UserGroupRelation(Long userId, Long groupId, UserGroupRole role) { - this.userId = userId; - this.groupId = groupId; - this.role = role; - } - -} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java deleted file mode 100644 index 62d9cb28ea..0000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.hibernate.wherejointable; - -public enum UserGroupRole { - - MEMBER, MODERATOR - -} diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java diff --git a/persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java deleted file mode 100644 index 3bc5a6e12a..0000000000 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.hibernate.oneToMany.main; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.service.ServiceRegistry; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; - -public class HibernateOneToManyAnnotationMainIntegrationTest { - - private static SessionFactory sessionFactory; - - private Session session; - - public HibernateOneToManyAnnotationMainIntegrationTest() { - } - - @BeforeClass - public static void beforeTests() { - Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) - .setProperty("hibernate.dialect", H2Dialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") - .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() - .applySettings(configuration.getProperties()).build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - } - - @Test - public void givenSession_checkIfDatabaseIsEmpty() { - Cart cart = (Cart) session.get(Cart.class, new Long(1)); - assertNull(cart); - - } - - @Test - public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { - Cart cart = new Cart(); - Set cartItems = new HashSet<>(); - cartItems = cart.getItems(); - Assert.assertNull(cartItems); - Items item1 = new Items(); - item1.setCart(cart); - assertNotNull(item1); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - assertNotNull(itemsSet); - cart.setItems(itemsSet); - assertNotNull(cart); - session.persist(cart); - session.getTransaction().commit(); - session.close(); - - session = sessionFactory.openSession(); - session.beginTransaction(); - cart = (Cart) session.get(Cart.class, new Long(1)); - assertNotNull(cart); - } - - @After - public void tearDown() { - session.getTransaction().commit(); - session.close(); - } - - @AfterClass - public static void afterTests() { - sessionFactory.close(); - } - -} diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java deleted file mode 100644 index 93783216ce..0000000000 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.baeldung.hibernate.wherejointable; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.service.ServiceRegistry; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -public class HibernateWhereJoinTableIntegrationTest { - - private static SessionFactory sessionFactory; - - private Session session; - - /** - * Test data - */ - private User user1; - private User user2; - private User user3; - private Group group1; - private Group group2; - - @BeforeClass - public static void beforeTests() { - Configuration configuration = new Configuration().addAnnotatedClass(User.class) - .addAnnotatedClass(Group.class) - .addAnnotatedClass(UserGroupRelation.class) - .setProperty("hibernate.dialect", H2Dialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") - .setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() - .applySettings(configuration.getProperties()) - .build(); - - sessionFactory = configuration.buildSessionFactory(serviceRegistry); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - - user1 = new User("user1"); - user2 = new User("user2"); - user3 = new User("user3"); - - group1 = new Group("group1"); - group2 = new Group("group2"); - - session.save(group1); - session.save(group2); - - session.save(user1); - session.save(user2); - session.save(user3); - - saveRelation(user1, group1, UserGroupRole.MODERATOR); - saveRelation(user2, group1, UserGroupRole.MODERATOR); - saveRelation(user3, group1, UserGroupRole.MEMBER); - - saveRelation(user1, group2, UserGroupRole.MEMBER); - saveRelation(user2, group2, UserGroupRole.MODERATOR); - } - - @After - public void tearDown() { - session.getTransaction().commit(); - session.close(); - } - - @AfterClass - public static void afterTests() { - sessionFactory.close(); - } - - @Test - public void givenUser1_getGroups_returnsAllGroups() { - List groups = user1.getGroups(); - assertEquals(2, groups.size()); - - assertTrue(groups.contains(group1)); - assertTrue(groups.contains(group2)); - } - - @Test - public void givenUser1_getModeratorGroups_returnsOnlyModeratorGroups() { - List groups = user1.getModeratorGroups(); - assertEquals(1, groups.size()); - - assertTrue(groups.contains(group1)); - } - - private void saveRelation(User user, Group group, UserGroupRole role) { - UserGroupRelation relation = new UserGroupRelation(user.getId(), group.getId(), role); - - session.save(relation); - session.flush(); - session.refresh(user); - session.refresh(group); - } - -} diff --git a/persistence-modules/hibernate5-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/resources/hibernate.properties rename to persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties diff --git a/persistence-modules/hibernate5-mapping/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/resources/lifecycle-init.sql rename to persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql diff --git a/persistence-modules/hibernate5-mapping/src/test/resources/profile.png b/persistence-modules/hibernate-mapping/src/test/resources/profile.png similarity index 100% rename from persistence-modules/hibernate5-mapping/src/test/resources/profile.png rename to persistence-modules/hibernate-mapping/src/test/resources/profile.png From e1d9086ef76e62eed66de4aa35c03b2e2015a145 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:54:52 +0530 Subject: [PATCH 15/17] JAVA-4: Updated README for original module hibernate5 --- persistence-modules/hibernate5/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 7b5e3bb189..b7a254d836 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -1,6 +1,6 @@ ## Hibernate 5 -This module contains articles about Hibernate 5. +This module contains articles about Hibernate 5. Let's not add more articles here, we should not be creating a -2 out of it. Please add to other existing hibernate-* modules, or create a new one. ### Relevant articles: @@ -12,5 +12,4 @@ This module contains articles about Hibernate 5. - [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) - [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) -- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) -- [[Next -->]](/hibernate5-2) \ No newline at end of file +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) \ No newline at end of file From 6023de1b93d8359df2a916b4af265e31102fd028 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:55:19 +0530 Subject: [PATCH 16/17] JAVA-4: Updated module pom --- persistence-modules/pom.xml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 2e9b033b79..f1b7c407bd 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -23,11 +23,10 @@ hibernate5 hibernate-mapping hibernate-ogm - hibernate5-mapping - hibernate5-annotations - hibernate5-jpa - hibernate5-queries - hibernate5-enterprise + hibernate-annotations + hibernate-jpa + hibernate-queries + hibernate-enterprise influxdb java-cassandra java-cockroachdb From 12034cd05ceab769408c8b262d072b2b2e0c3650 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 15 Mar 2020 12:56:22 +0530 Subject: [PATCH 17/17] JAVA-4: Included article in README for which code belongs here --- persistence-modules/spring-hibernate-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index a74600a47f..4a97368537 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -12,3 +12,4 @@ This module contains articles about Hibernate 5 with Spring. - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)