[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>
<maven.deploy.skip>true</maven.deploy.skip>
<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>
<hsqldb.version>2.3.4</hsqldb.version>
</properties>

View File

@ -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<Class<?>> 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<Class<?>> classes) {
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();
for (Class<?> clazz: classes) {
metadataSources = metadataSources.addAnnotatedClass(clazz);
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
return configureServiceRegistry(getProperties());
Metadata metadata = metadataSources
.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)
.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")));
}
}

View File

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

View File

@ -7,29 +7,30 @@ 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")
.applySettings(dbSettings())
.build();
Metadata metadata = new MetadataSources(serviceRegistry)
@ -37,15 +38,20 @@ public class HibernateAnnotationUtil {
.addAnnotatedClass(CartOIO.class)
.addAnnotatedClass(Item.class)
.addAnnotatedClass(ItemOIO.class)
.getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
.build();
.buildMetadata();
return metadata.getSessionFactoryBuilder().build();
} catch (Throwable ex) {
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
return metadata.buildSessionFactory();
}
private static Map<String, String> dbSettings() {
Map<String, String> 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;
}
}

View File

@ -12,7 +12,7 @@ import javax.persistence.ManyToMany;
import org.hibernate.annotations.WhereJoinTable;
@Entity
@Entity(name = "users")
public class User {
@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;
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<OfficeEmployee> 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();
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;
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();
}
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