init submit for H2 test about hibernate annotations

This commit is contained in:
YuCheng Hu 2020-04-11 00:40:29 -04:00
parent 236372322d
commit 31723ab63e
9 changed files with 435 additions and 0 deletions

View File

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

View File

@ -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();
}
}

View File

@ -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<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items();
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
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();
}
}

View File

@ -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<Group> groups = user1.getGroups();
assertEquals(2, groups.size());
assertTrue(groups.contains(group1));
assertTrue(groups.contains(group2));
}
@Test
public void givenUser1_getModeratorGroups_returnsOnlyModeratorGroups() {
List<Group> 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);
}
}

View File

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

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</layout>
</appender>
<logger name="org.hibernate">
<level value="info" />
</logger>
<logger name="org.hibernate.SQL">
<level value="debug" />
</logger>
<logger name="org.hibernate.type.descriptor.sql">
<level value="trace" />
</logger>
<logger name="org.hibernate.stat">
<level value="debug" />
</logger>
<root>
<priority value ="info" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="org.hibernate" level="info"/>
<Logger name="org.hibernate.SQL" level="debug"/>
<Logger name="org.hibernate.type.descriptor.sql" level="trace"/>
<Logger name="org.hibernate.stat" level="debug" />
<Root level="info" additivity="false">
<AppenderRef ref="console" />
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.hibernate" level="INFO" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.type.descriptor.sql" level="TRACE" />
<logger name="org.hibernate.stat" level="DEBUG" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB