[BAEL-14841] - Fixed tests in hibernate-mapping, hibernate5, java-jpa modules

This commit is contained in:
amit2103 2019-05-30 01:33:20 +05:30
parent 6e4e729156
commit 9e470968e9
25 changed files with 165 additions and 95 deletions

View File

@ -12,16 +12,12 @@ import java.net.URL;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory(Strategy strategy) {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory(strategy);
}
return sessionFactory;
return buildSessionFactory(strategy);
}
private static SessionFactory buildSessionFactory(Strategy strategy) {

View File

@ -2,12 +2,12 @@ package com.baeldung.hibernate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public enum Strategy {
//See that the classes belongs to different packages
MAP_KEY_COLUMN_BASED(Collections.singletonList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class)),
MAP_KEY_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class,
com.baeldung.hibernate.basicannotation.Course.class)),
MAP_KEY_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkey.Item.class,
com.baeldung.hibernate.persistmaps.mapkey.Order.class,com.baeldung.hibernate.persistmaps.mapkey.User.class)),
MAP_KEY_JOIN_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller.class,

View File

@ -1,18 +1,19 @@
package com.baeldung.hibernate.basicannotation;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.basicannotation.Course;
import com.baeldung.hibernate.Strategy;
import org.hibernate.PropertyValueException;
import java.io.IOException;
import javax.persistence.PersistenceException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.SessionFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
public class BasicAnnotationIntegrationTest {
@ -48,7 +49,7 @@ public class BasicAnnotationIntegrationTest {
}
@Test(expected = PropertyValueException.class)
@Test(expected = PersistenceException.class)
public void givenACourse_whenCourseNameAbsent_shouldFail() {
Course course = new Course();

View File

@ -37,6 +37,11 @@
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.opengeo</groupId>
<artifactId>geodb</artifactId>
<version>${geodb.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
@ -99,6 +104,14 @@
</resource>
</resources>
</build>
<repositories>
<repository>
<id>geodb-repo</id>
<name>GeoDB repository</name>
<url>http://repo.boundlessgeo.com/main/</url>
</repository>
</repositories>
<properties>
<hibernate.version>5.3.7.Final</hibernate.version>
@ -106,6 +119,7 @@
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<assertj-core.version>3.8.0</assertj-core.version>
<openjdk-jmh.version>1.21</openjdk-jmh.version>
<geodb.version>0.9</geodb.version>
</properties>
</project>

View File

@ -5,27 +5,25 @@ 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.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.*;
import com.baeldung.hibernate.pojo.Person;
import com.baeldung.hibernate.pojo.inheritance.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.pojo.Course;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
@ -36,6 +34,7 @@ import com.baeldung.hibernate.pojo.Person;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.baeldung.hibernate.pojo.Post;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Student;
import com.baeldung.hibernate.pojo.TemporalValues;
@ -52,7 +51,6 @@ import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
@ -61,11 +59,8 @@ public class HibernateUtil {
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
return sessionFactory;
ServiceRegistry serviceRegistry = configureServiceRegistry();
return makeSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
@ -114,6 +109,10 @@ public class HibernateUtil {
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)

View File

@ -19,7 +19,7 @@ public class Email {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee employee;
private OfficialEmployee employee;
public Long getId() {
return id;
@ -37,11 +37,11 @@ public class Email {
this.address = address;
}
public Employee getEmployee() {
public OfficialEmployee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
public void setEmployee(OfficialEmployee employee) {
this.employee = employee;
}
}

View File

@ -21,7 +21,7 @@ public class Office {
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
private Address address;
private OfficeAddress address;
public Long getId() {
return id;
@ -31,11 +31,11 @@ public class Office {
this.id = id;
}
public Address getAddress() {
public OfficeAddress getAddress() {
return address;
}
public void setAddress(Address address) {
public void setAddress(OfficeAddress address) {
this.address = address;
}
}

View File

@ -7,7 +7,7 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Address {
public class OfficeAddress {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)

View File

@ -9,7 +9,7 @@ import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Employee {
public class OfficialEmployee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)

View File

@ -19,10 +19,7 @@ public class HibernateUtil {
}
public static SessionFactory getSessionFactory(Strategy strategy) {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory(strategy);
}
return sessionFactory;
return buildSessionFactory(strategy);
}
private static SessionFactory buildSessionFactory(Strategy strategy) {

View File

@ -2,6 +2,7 @@ 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;
@ -13,6 +14,7 @@ public class PointEntity {
@GeneratedValue
private Long id;
@Column(columnDefinition="BINARY(2048)")
private Point point;
public PointEntity() {

View File

@ -129,7 +129,7 @@ public class DynamicMappingIntegrationTest {
employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(3);
assertThat(employees).hasSize(0);
}

View File

@ -4,7 +4,10 @@ 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;
@ -24,6 +27,8 @@ 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;
@ -34,6 +39,7 @@ public class HibernateSpatialIntegrationTest {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
session.doWork(conn -> { GeoDB.InitGeoDB(conn); });
}
@After
@ -141,4 +147,15 @@ public class HibernateSpatialIntegrationTest {
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;
}
}

View File

@ -45,7 +45,7 @@ public class TypeSafeCriteriaIntegrationTest {
CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);
Root<Student> root = criteriaQuery.from(Student.class);
criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965));
criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965));
Query<Student> query = session.createQuery(criteriaQuery);
List<Student> results = query.getResultList();

View File

@ -32,7 +32,7 @@ public class JoinColumnIntegrationTest {
public void givenOfficeEntity_setAddress_shouldPersist() {
Office office = new Office();
Address address = new Address();
OfficeAddress address = new OfficeAddress();
address.setZipCode("11-111");
office.setAddress(address);
@ -43,7 +43,7 @@ public class JoinColumnIntegrationTest {
@Test
public void givenEmployeeEntity_setEmails_shouldPersist() {
Employee employee = new Employee();
OfficialEmployee employee = new OfficialEmployee();
Email email = new Email();
email.setAddress("example@email.com");

View File

@ -1,17 +1,23 @@
package com.baeldung.hibernate.optimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.OptimisticLockException;
import java.io.IOException;
import java.util.Arrays;
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 {
@ -124,11 +130,17 @@ public class OptimisticLockingIntegrationTest {
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -2,6 +2,9 @@ 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;
@ -10,6 +13,8 @@ import java.io.IOException;
import java.util.Arrays;
public class BasicPessimisticLockingIntegrationTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void setUp() throws IOException {
@ -140,12 +145,18 @@ public class BasicPessimisticLockingIntegrationTest {
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,6 +1,9 @@
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;
@ -13,6 +16,8 @@ import java.util.HashMap;
import java.util.Map;
public class PessimisticLockScopesIntegrationTest {
private static SessionFactory sessionFactory;
@Test
public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException {
@ -104,12 +109,17 @@ public class PessimisticLockScopesIntegrationTest {
protected EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,10 +1,14 @@
hibernate.connection.driver_class=org.postgresql.Driver
hibernate.connection.url=jdbc:postgresql://localhost:5432/test
hibernate.connection.username=postgres
hibernate.connection.password=thule
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=thule
jdbc.password=
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800

View File

@ -1,5 +1,5 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
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

View File

@ -1,10 +1,14 @@
hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial
hibernate.connection.username=root
hibernate.connection.password=pass
hibernate.connection.pool_size=5
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.format_sql=true
hibernate.max_fetch_depth=5
hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800

View File

@ -9,6 +9,7 @@
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
<class>com.baeldung.sqlresultsetmapping.Employee</class>
<class>com.baeldung.jpa.basicannotation.Course</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"

View File

@ -15,3 +15,7 @@ INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (1, 'FRIDAY');
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (2, 'SATURDAY');
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'MONDAY');
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'FRIDAY');
CREATE TABLE COURSE
(id BIGINT,
name VARCHAR(10));

View File

@ -1,16 +1,13 @@
package com.baeldung.jpa.basicannotation;
import org.hibernate.PropertyValueException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import javax.persistence.PersistenceException;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class BasicAnnotationIntegrationTest {
@ -18,9 +15,10 @@ public class BasicAnnotationIntegrationTest {
private static EntityManagerFactory entityManagerFactory;
@BeforeClass
public void setup() {
public static void setup() {
entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
}
@Test
@ -34,7 +32,7 @@ public class BasicAnnotationIntegrationTest {
}
@Test(expected = PropertyValueException.class)
@Test(expected = PersistenceException.class)
public void givenACourse_whenCourseNameAbsent_shouldFail() {
Course course = new Course();
@ -44,7 +42,7 @@ public class BasicAnnotationIntegrationTest {
}
@AfterClass
public void destroy() {
public static void destroy() {
if (entityManager != null) {
entityManager.close();