From b03e1b3216700a890cdd8bba8cf5d6e294bb4a28 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Wed, 4 May 2022 18:15:23 +0100 Subject: [PATCH] [JAVA-11332] Upgrade H2 version and fix tests (#12056) * [JAVA-11332] Upgrade H2 version and fix tests * [JAVA-11332] Revert formatting changes * [JAVA-11332] Remove config files and code clean up --- .../hibernate-annotations/pom.xml | 2 +- .../com/baeldung/hibernate/HibernateUtil.java | 75 ++++++++----------- .../hibernate/customtypes/OfficeEmployee.java | 1 - .../config/HibernateAnnotationUtil.java | 58 +++++++------- .../hibernate/wherejointable/User.java | 2 +- .../resources/hibernate-annotation.cfg.xml | 18 ----- ... HibernateCustomTypesIntegrationTest.java} | 56 ++++++++++---- .../joincolumn/JoinColumnIntegrationTest.java | 50 +++++++++++-- .../resources/hibernate-spatial.properties | 14 ---- 9 files changed, 150 insertions(+), 126 deletions(-) delete mode 100644 persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml rename persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/{HibernateCustomTypesManualTest.java => HibernateCustomTypesIntegrationTest.java} (52%) delete mode 100644 persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index 023e5aa30f..dc5f245f22 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -85,7 +85,7 @@ 5.6.7.Final true 2.1.7.RELEASE - 1.4.200 + 2.1.212 9.0.0.M26 2.3.4 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java index afe2aeac89..65d9f249fa 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,10 +1,5 @@ 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; @@ -12,62 +7,58 @@ 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; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.List; +import java.util.Properties; + +import static java.util.Objects.requireNonNull; public class HibernateUtil { - private static String PROPERTY_FILE_NAME; - public static SessionFactory getSessionFactory() throws IOException { - return getSessionFactory(null); + public static SessionFactory getSessionFactory(String propertyFileName, List> classes) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(propertyFileName); + return makeSessionFactory(serviceRegistry, classes); } - 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) { + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry, List> classes) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); + for (Class clazz: classes) { + metadataSources = metadataSources.addAnnotatedClass(clazz); + } - 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(); + Metadata metadata = metadataSources + .getMetadataBuilder() + .build(); + return metadata.getSessionFactoryBuilder().build(); } - private static ServiceRegistry configureServiceRegistry() throws IOException { - return configureServiceRegistry(getProperties()); + private static ServiceRegistry configureServiceRegistry(String propertyFileName) throws IOException { + return configureServiceRegistry(getProperties(propertyFileName)); } - private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + private static ServiceRegistry configureServiceRegistry(Properties properties) { return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } - public static Properties getProperties() throws IOException { + public static Properties getProperties(String propertyFileName) 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())) { + + String file = getResourceURL(propertyFileName).getFile(); + + try (FileInputStream inputStream = new FileInputStream(file)) { properties.load(inputStream); } + return properties; } + + private static URL getResourceURL(String propertyFileName) { + return requireNonNull(Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(propertyFileName, "hibernate.properties"))); + } } \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java index 3ca06e4316..1ffeb0b99d 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java @@ -1,6 +1,5 @@ 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; diff --git a/persistence-modules/hibernate-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 index 6c94d34339..ef82c1c9ad 100644 --- a/persistence-modules/hibernate-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 @@ -7,45 +7,51 @@ import com.baeldung.hibernate.oneToMany.model.ItemOIO; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; public class HibernateAnnotationUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(HibernateAnnotationUtil.class); + private static final SessionFactory SESSION_FACTORY = buildSessionFactory(); - private static SessionFactory sessionFactory; + /** + * Utility class + */ + private HibernateAnnotationUtil() { + } public static SessionFactory getSessionFactory() { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(); - } - return sessionFactory; + return SESSION_FACTORY; } private static SessionFactory buildSessionFactory() { - try { - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() - .configure("hibernate-annotation.cfg.xml") - .build(); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(dbSettings()) + .build(); - Metadata metadata = new MetadataSources(serviceRegistry) - .addAnnotatedClass(Cart.class) - .addAnnotatedClass(CartOIO.class) - .addAnnotatedClass(Item.class) - .addAnnotatedClass(ItemOIO.class) - .getMetadataBuilder() - .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) - .build(); + Metadata metadata = new MetadataSources(serviceRegistry) + .addAnnotatedClass(Cart.class) + .addAnnotatedClass(CartOIO.class) + .addAnnotatedClass(Item.class) + .addAnnotatedClass(ItemOIO.class) + .buildMetadata(); - return metadata.getSessionFactoryBuilder().build(); + return metadata.buildSessionFactory(); + } - } catch (Throwable ex) { - LOGGER.error("Initial SessionFactory creation failed.", ex); - throw new ExceptionInInitializerError(ex); - } + private static Map dbSettings() { + Map dbSettings = new HashMap<>(); + dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many"); + dbSettings.put(Environment.USER, "sa"); + dbSettings.put(Environment.PASS, ""); + dbSettings.put(Environment.DRIVER, "org.h2.Driver"); + dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + dbSettings.put(Environment.SHOW_SQL, "true"); + dbSettings.put(Environment.HBM2DDL_AUTO, "create"); + return dbSettings; } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java index 7fc077eeb2..3029aae640 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java @@ -12,7 +12,7 @@ import javax.persistence.ManyToMany; import org.hibernate.annotations.WhereJoinTable; -@Entity +@Entity(name = "users") public class User { @Id diff --git a/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml deleted file mode 100644 index 6e845b3781..0000000000 --- a/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - org.h2.Driver - sa - - jdbc:h2:mem:spring_hibernate_one_to_many - - org.hibernate.dialect.H2Dialect - thread - true - create - - diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java similarity index 52% rename from persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java index 63dc6330be..460b65ee12 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java @@ -1,20 +1,27 @@ package com.baeldung.hibernate.customtypes; -import com.baeldung.hibernate.HibernateUtil; import org.hibernate.SessionFactory; -import org.hibernate.query.Query; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Environment; +import org.hibernate.service.ServiceRegistry; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; +import javax.persistence.TypedQuery; import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -public class HibernateCustomTypesManualTest { +public class HibernateCustomTypesIntegrationTest { @Test - public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() throws IOException { + public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() { final OfficeEmployee e = new OfficeEmployee(); e.setDateOfJoining(LocalDate.now()); @@ -39,13 +46,13 @@ public class HibernateCustomTypesManualTest { doInHibernate(this::sessionFactory, session -> { session.save(e); boolean contains = session.contains(e); - Assert.assertTrue(contains); + assertTrue(contains); }); } @Test - public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() throws IOException { + public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() { final OfficeEmployee e = new OfficeEmployee(); e.setDateOfJoining(LocalDate.now()); @@ -69,22 +76,39 @@ public class HibernateCustomTypesManualTest { doInHibernate(this::sessionFactory, session -> { session.save(e); - Query query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode"); + TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class); query.setParameter("pinCode",100); - int size = query.list().size(); + int size = query.getResultList().size(); - Assert.assertEquals(1, size); + assertEquals(1, size); }); } private SessionFactory sessionFactory() { - try { - return HibernateUtil.getSessionFactory("hibernate-customtypes.properties"); - } catch (IOException e) { - e.printStackTrace(); - } + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(getProperties()) + .build(); - return null; + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + Metadata metadata = metadataSources + .addAnnotatedClass(OfficeEmployee.class) + .getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.buildSessionFactory(); + } + + private static Map getProperties() { + Map dbSettings = new HashMap<>(); + dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); + dbSettings.put(Environment.USER, "sa"); + dbSettings.put(Environment.PASS, ""); + dbSettings.put(Environment.DRIVER, "org.h2.Driver"); + dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + dbSettings.put(Environment.SHOW_SQL, "true"); + dbSettings.put(Environment.HBM2DDL_AUTO, "create"); + return dbSettings; } } diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java index 0998ff1d90..37125e8b15 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -1,14 +1,21 @@ package com.baeldung.hibernate.joincolumn; -import com.baeldung.hibernate.HibernateUtil; -import java.io.IOException; +import com.baeldung.hibernate.customtypes.LocalDateStringType; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.Transaction; - +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.util.HashMap; +import java.util.Map; public class JoinColumnIntegrationTest { @@ -16,9 +23,8 @@ public class JoinColumnIntegrationTest { private Transaction transaction; @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") - .openSession(); + public void setUp() { + session = sessionFactory().openSession(); transaction = session.beginTransaction(); } @@ -54,4 +60,34 @@ public class JoinColumnIntegrationTest { session.clear(); } -} \ No newline at end of file + private SessionFactory sessionFactory() { + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(getProperties()) + .build(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + Metadata metadata = metadataSources + .addAnnotatedClass(Email.class) + .addAnnotatedClass(Office.class) + .addAnnotatedClass(OfficeAddress.class) + .addAnnotatedClass(OfficialEmployee.class) + .getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.buildSessionFactory(); + } + + private static Map getProperties() { + Map dbSettings = new HashMap<>(); + dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1"); + dbSettings.put(Environment.USER, "sa"); + dbSettings.put(Environment.PASS, ""); + dbSettings.put(Environment.DRIVER, "org.h2.Driver"); + dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + dbSettings.put(Environment.SHOW_SQL, "true"); + dbSettings.put(Environment.HBM2DDL_AUTO, "create"); + return dbSettings; + } + +} diff --git a/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties deleted file mode 100644 index 1657c838e3..0000000000 --- a/persistence-modules/hibernate-annotations/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