[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
This commit is contained in:
Haroon Khan 2022-05-04 18:15:23 +01:00 committed by GitHub
parent 9990d103cd
commit b03e1b3216
9 changed files with 150 additions and 126 deletions

View File

@ -85,7 +85,7 @@
<hibernate-core.version>5.6.7.Final</hibernate-core.version> <hibernate-core.version>5.6.7.Final</hibernate-core.version>
<maven.deploy.skip>true</maven.deploy.skip> <maven.deploy.skip>true</maven.deploy.skip>
<spring-boot.version>2.1.7.RELEASE</spring-boot.version> <spring-boot.version>2.1.7.RELEASE</spring-boot.version>
<h2.version>1.4.200</h2.version> <h2.version>2.1.212</h2.version>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version> <tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<hsqldb.version>2.3.4</hsqldb.version> <hsqldb.version>2.3.4</hsqldb.version>
</properties> </properties>

View File

@ -1,10 +1,5 @@
package com.baeldung.hibernate; 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.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
@ -12,62 +7,58 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.joincolumn.Email; import java.io.FileInputStream;
import com.baeldung.hibernate.joincolumn.Office; import java.io.IOException;
import com.baeldung.hibernate.joincolumn.OfficeAddress; import java.net.URL;
import java.util.List;
import java.util.Properties;
import static java.util.Objects.requireNonNull;
public class HibernateUtil { public class HibernateUtil {
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException { public static SessionFactory getSessionFactory(String propertyFileName, List<Class<?>> classes) throws IOException {
return getSessionFactory(null); ServiceRegistry serviceRegistry = configureServiceRegistry(propertyFileName);
return makeSessionFactory(serviceRegistry, classes);
} }
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry, List<Class<?>> classes) {
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 metadataSources = new MetadataSources(serviceRegistry);
for (Class<?> clazz: classes) {
metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources = metadataSources.addAnnotatedClass(clazz);
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 { Metadata metadata = metadataSources
return configureServiceRegistry(getProperties()); .getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder().build();
} }
private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { private static ServiceRegistry configureServiceRegistry(String propertyFileName) throws IOException {
return configureServiceRegistry(getProperties(propertyFileName));
}
private static ServiceRegistry configureServiceRegistry(Properties properties) {
return new StandardServiceRegistryBuilder().applySettings(properties) return new StandardServiceRegistryBuilder().applySettings(properties)
.build(); .build();
} }
public static Properties getProperties() throws IOException { public static Properties getProperties(String propertyFileName) throws IOException {
Properties properties = new Properties(); Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader() String file = getResourceURL(propertyFileName).getFile();
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { try (FileInputStream inputStream = new FileInputStream(file)) {
properties.load(inputStream); properties.load(inputStream);
} }
return properties; return properties;
} }
private static URL getResourceURL(String propertyFileName) {
return requireNonNull(Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(propertyFileName, "hibernate.properties")));
}
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.hibernate.customtypes; package com.baeldung.hibernate.customtypes;
import com.baeldung.hibernate.pojo.Phone;
import org.hibernate.annotations.Columns; import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type; import org.hibernate.annotations.Type;

View File

@ -7,29 +7,30 @@ import com.baeldung.hibernate.oneToMany.model.ItemOIO;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.HashMap;
import java.util.Map;
public class HibernateAnnotationUtil { 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() { public static SessionFactory getSessionFactory() {
if (sessionFactory == null) { return SESSION_FACTORY;
sessionFactory = buildSessionFactory();
}
return sessionFactory;
} }
private static SessionFactory buildSessionFactory() { private static SessionFactory buildSessionFactory() {
try {
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate-annotation.cfg.xml") .applySettings(dbSettings())
.build(); .build();
Metadata metadata = new MetadataSources(serviceRegistry) Metadata metadata = new MetadataSources(serviceRegistry)
@ -37,15 +38,20 @@ public class HibernateAnnotationUtil {
.addAnnotatedClass(CartOIO.class) .addAnnotatedClass(CartOIO.class)
.addAnnotatedClass(Item.class) .addAnnotatedClass(Item.class)
.addAnnotatedClass(ItemOIO.class) .addAnnotatedClass(ItemOIO.class)
.getMetadataBuilder() .buildMetadata();
.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder().build(); return metadata.buildSessionFactory();
}
} catch (Throwable ex) { private static Map<String, String> dbSettings() {
LOGGER.error("Initial SessionFactory creation failed.", ex); Map<String, String> dbSettings = new HashMap<>();
throw new ExceptionInInitializerError(ex); 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;
} }
} }

View File

@ -12,7 +12,7 @@ import javax.persistence.ManyToMany;
import org.hibernate.annotations.WhereJoinTable; import org.hibernate.annotations.WhereJoinTable;
@Entity @Entity(name = "users")
public class User { public class User {
@Id @Id

View File

@ -1,18 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.connection.url">jdbc:h2:mem:spring_hibernate_one_to_many</property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>

View File

@ -1,20 +1,27 @@
package com.baeldung.hibernate.customtypes; package com.baeldung.hibernate.customtypes;
import com.baeldung.hibernate.HibernateUtil;
import org.hibernate.SessionFactory; 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.Assert;
import org.junit.Test; import org.junit.Test;
import java.io.IOException; import javax.persistence.TypedQuery;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; 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 @Test
public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() throws IOException { public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() {
final OfficeEmployee e = new OfficeEmployee(); final OfficeEmployee e = new OfficeEmployee();
e.setDateOfJoining(LocalDate.now()); e.setDateOfJoining(LocalDate.now());
@ -39,13 +46,13 @@ public class HibernateCustomTypesManualTest {
doInHibernate(this::sessionFactory, session -> { doInHibernate(this::sessionFactory, session -> {
session.save(e); session.save(e);
boolean contains = session.contains(e); boolean contains = session.contains(e);
Assert.assertTrue(contains); assertTrue(contains);
}); });
} }
@Test @Test
public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() throws IOException { public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() {
final OfficeEmployee e = new OfficeEmployee(); final OfficeEmployee e = new OfficeEmployee();
e.setDateOfJoining(LocalDate.now()); e.setDateOfJoining(LocalDate.now());
@ -69,22 +76,39 @@ public class HibernateCustomTypesManualTest {
doInHibernate(this::sessionFactory, session -> { doInHibernate(this::sessionFactory, session -> {
session.save(e); session.save(e);
Query query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode"); TypedQuery<OfficeEmployee> query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class);
query.setParameter("pinCode",100); query.setParameter("pinCode",100);
int size = query.list().size(); int size = query.getResultList().size();
Assert.assertEquals(1, size); assertEquals(1, size);
}); });
} }
private SessionFactory sessionFactory() { private SessionFactory sessionFactory() {
try { ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
return HibernateUtil.getSessionFactory("hibernate-customtypes.properties"); .applySettings(getProperties())
} catch (IOException e) { .build();
e.printStackTrace();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
Metadata metadata = metadataSources
.addAnnotatedClass(OfficeEmployee.class)
.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
return metadata.buildSessionFactory();
} }
return null; private static Map<String, String> getProperties() {
Map<String, String> 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;
} }
} }

View File

@ -1,14 +1,21 @@
package com.baeldung.hibernate.joincolumn; package com.baeldung.hibernate.joincolumn;
import com.baeldung.hibernate.HibernateUtil; import com.baeldung.hibernate.customtypes.LocalDateStringType;
import java.io.IOException;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction; 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.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class JoinColumnIntegrationTest { public class JoinColumnIntegrationTest {
@ -16,9 +23,8 @@ public class JoinColumnIntegrationTest {
private Transaction transaction; private Transaction transaction;
@Before @Before
public void setUp() throws IOException { public void setUp() {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") session = sessionFactory().openSession();
.openSession();
transaction = session.beginTransaction(); transaction = session.beginTransaction();
} }
@ -54,4 +60,34 @@ public class JoinColumnIntegrationTest {
session.clear(); session.clear();
} }
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<String, String> getProperties() {
Map<String, String> 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;
}
} }

View File

@ -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