JAVA-4: Removed hibernate5-mapping; merged into to hibernate-mapping
This commit is contained in:
+78
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.query.Query;
|
||||
import org.hibernate.transform.Transformers;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.hibernate.entities.Department;
|
||||
import com.baeldung.hibernate.pojo.Result;
|
||||
|
||||
public class CustomClassIntegrationTest {
|
||||
|
||||
private Session session;
|
||||
|
||||
private Transaction transaction;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory().openSession();
|
||||
transaction = session.beginTransaction();
|
||||
session.createNativeQuery("delete from department").executeUpdate();
|
||||
Department department = new Department("Sales");
|
||||
DeptEmployee employee = new DeptEmployee("John Smith", "001", department);
|
||||
session.persist(department);
|
||||
session.persist(employee);
|
||||
transaction.commit();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAllManagersAreSelected_ThenObjectGraphIsReturned() {
|
||||
Query<DeptEmployee> query = session.createQuery("from com.baeldung.hibernate.entities.DeptEmployee");
|
||||
List<DeptEmployee> deptEmployees = query.list();
|
||||
DeptEmployee deptEmployee = deptEmployees.get(0);
|
||||
assertEquals("John Smith", deptEmployee.getName());
|
||||
assertEquals("Sales", deptEmployee.getDepartment().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIndividualPropertiesAreSelected_ThenObjectArrayIsReturned() {
|
||||
Query query = session.createQuery("select m.name, m.department.name from com.baeldung.hibernate.entities.DeptEmployee m");
|
||||
List managers = query.list();
|
||||
Object[] manager = (Object[]) managers.get(0);
|
||||
assertEquals("John Smith", manager[0]);
|
||||
assertEquals("Sales", manager[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResultConstructorInSelect_ThenListOfResultIsReturned() {
|
||||
Query<Result> query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) "
|
||||
+ "from DeptEmployee m");
|
||||
List<Result> results = query.list();
|
||||
Result result = results.get(0);
|
||||
assertEquals("John Smith", result.getEmployeeName());
|
||||
assertEquals("Sales", result.getDepartmentName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResultTransformerOnQuery_ThenListOfResultIsReturned() {
|
||||
Query query = session.createQuery("select m.name as employeeName, m.department.name as departmentName "
|
||||
+ "from com.baeldung.hibernate.entities.DeptEmployee m");
|
||||
query.setResultTransformer(Transformers.aliasToBean(Result.class));
|
||||
List<Result> results = query.list();
|
||||
Result result = results.get(0);
|
||||
assertEquals("John Smith", result.getEmployeeName());
|
||||
assertEquals("Sales", result.getDepartmentName());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Employee;
|
||||
import com.baeldung.hibernate.pojo.EntityDescription;
|
||||
import com.baeldung.hibernate.pojo.Phone;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class DynamicMappingIntegrationTest {
|
||||
|
||||
private Session session;
|
||||
|
||||
private Transaction transaction;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory().openSession();
|
||||
transaction = session.beginTransaction();
|
||||
|
||||
session.createNativeQuery("delete from phone").executeUpdate();
|
||||
session.createNativeQuery("delete from employee").executeUpdate();
|
||||
|
||||
transaction.commit();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() {
|
||||
Employee employee = new Employee(10_000L, 25);
|
||||
assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L);
|
||||
|
||||
session.save(employee);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
employee = session.get(Employee.class, employee.getId());
|
||||
assertThat(employee.getTax()).isEqualTo(2_500L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
|
||||
Employee employee = new Employee();
|
||||
|
||||
session.save(employee);
|
||||
session.clear();
|
||||
|
||||
employee = session.find(Employee.class, employee.getId());
|
||||
assertThat(employee).isNotNull();
|
||||
|
||||
employee.setDeleted(true);
|
||||
session.flush();
|
||||
|
||||
employee = session.find(Employee.class, employee.getId());
|
||||
assertThat(employee).isNotNull();
|
||||
|
||||
session.clear();
|
||||
|
||||
employee = session.find(Employee.class, employee.getId());
|
||||
assertThat(employee).isNull();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
|
||||
Employee employee = new Employee();
|
||||
Phone phone1 = new Phone("555-45-67");
|
||||
Phone phone2 = new Phone("555-89-01");
|
||||
employee.getPhones().add(phone1);
|
||||
employee.getPhones().add(phone2);
|
||||
|
||||
session.save(phone1);
|
||||
session.save(phone2);
|
||||
session.save(employee);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
employee = session.find(Employee.class, employee.getId());
|
||||
assertThat(employee.getPhones()).hasSize(2);
|
||||
|
||||
employee.getPhones().iterator().next().setDeleted(true);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
employee = session.find(Employee.class, employee.getId());
|
||||
assertThat(employee.getPhones()).hasSize(1);
|
||||
|
||||
List<Phone> fullPhoneList = session.createQuery("from Phone").getResultList();
|
||||
assertThat(fullPhoneList).hasSize(2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException {
|
||||
session.save(new Employee(10_000, 25));
|
||||
session.save(new Employee(12_000, 25));
|
||||
session.save(new Employee(15_000, 25));
|
||||
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
session.enableFilter("incomeLevelFilter")
|
||||
.setParameter("incomeLimit", 11_000);
|
||||
|
||||
List<Employee> employees = session.createQuery("from Employee").getResultList();
|
||||
|
||||
assertThat(employees).hasSize(2);
|
||||
|
||||
Employee employee = session.get(Employee.class, 1);
|
||||
assertThat(employee.getGrossIncome()).isEqualTo(10_000);
|
||||
|
||||
session.disableFilter("incomeLevelFilter");
|
||||
employees = session.createQuery("from Employee").getResultList();
|
||||
|
||||
assertThat(employees).hasSize(3);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() {
|
||||
Employee employee = new Employee();
|
||||
Phone phone1 = new Phone("555-45-67");
|
||||
Phone phone2 = new Phone("555-89-01");
|
||||
employee.getPhones().add(phone1);
|
||||
employee.getPhones().add(phone2);
|
||||
|
||||
EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee);
|
||||
EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1);
|
||||
EntityDescription phone2Description = new EntityDescription("Work phone", phone1);
|
||||
|
||||
session.save(phone1);
|
||||
session.save(phone2);
|
||||
session.save(employee);
|
||||
session.save(employeeDescription);
|
||||
session.save(phone1Description);
|
||||
session.save(phone2Description);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
List<EntityDescription> descriptions = session.createQuery("from EntityDescription").getResultList();
|
||||
|
||||
assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue();
|
||||
assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue();
|
||||
assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.pojo.inheritance.Bag;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Book;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Car;
|
||||
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Pen;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Pet;
|
||||
|
||||
public class InheritanceMappingIntegrationTest {
|
||||
private Session session;
|
||||
|
||||
private Transaction transaction;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory()
|
||||
.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubclasses_whenQuerySingleTableSuperclass_thenOk() {
|
||||
Book book = new Book(1, "1984", "George Orwell");
|
||||
session.save(book);
|
||||
Pen pen = new Pen(2, "my pen", "blue");
|
||||
session.save(pen);
|
||||
|
||||
assertThat(session.createQuery("from MyProduct")
|
||||
.getResultList()
|
||||
.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubclasses_whenQueryMappedSuperclass_thenOk() {
|
||||
MyEmployee emp = new MyEmployee(1, "john", "baeldung");
|
||||
session.save(emp);
|
||||
|
||||
assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Person")
|
||||
.getResultList()
|
||||
.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubclasses_whenQueryJoinedTableSuperclass_thenOk() {
|
||||
Pet pet = new Pet(1, "dog", "lassie");
|
||||
session.save(pet);
|
||||
|
||||
assertThat(session.createQuery("from Animal")
|
||||
.getResultList()
|
||||
.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubclasses_whenQueryTablePerClassSuperclass_thenOk() {
|
||||
Car car = new Car(1, "audi", "xyz");
|
||||
session.save(car);
|
||||
|
||||
assertThat(session.createQuery("from Vehicle")
|
||||
.getResultList()
|
||||
.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubclasses_whenQueryNonMappedInterface_thenOk() {
|
||||
Bag bag = new Bag(1, "large");
|
||||
session.save(bag);
|
||||
|
||||
assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item")
|
||||
.getResultList()
|
||||
.size()).isEqualTo(0);
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import com.baeldung.hibernate.pojo.TemporalValues;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.*;
|
||||
import java.util.Calendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TemporalValuesUnitTest {
|
||||
|
||||
private Session session;
|
||||
|
||||
private Transaction transaction;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory().withOptions()
|
||||
.jdbcTimeZone(TimeZone.getTimeZone("UTC"))
|
||||
.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
session.createNativeQuery("delete from temporalvalues").executeUpdate();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15"));
|
||||
temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14"));
|
||||
temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15"));
|
||||
assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14"));
|
||||
assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
|
||||
temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14"));
|
||||
temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332"));
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
|
||||
assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14"));
|
||||
assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
|
||||
Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
|
||||
calendarDate.set(Calendar.YEAR, 2017);
|
||||
calendarDate.set(Calendar.MONTH, 10);
|
||||
calendarDate.set(Calendar.DAY_OF_MONTH, 15);
|
||||
temporalValues.setCalendarDate(calendarDate);
|
||||
|
||||
Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
|
||||
calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322"));
|
||||
temporalValues.setCalendarTimestamp(calendarTimestamp);
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
|
||||
assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() {
|
||||
TemporalValues temporalValues = new TemporalValues();
|
||||
|
||||
temporalValues.setLocalDate(LocalDate.parse("2017-11-15"));
|
||||
temporalValues.setLocalTime(LocalTime.parse("15:30:18"));
|
||||
temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00"));
|
||||
|
||||
System.out.println("********"+OffsetTime.parse("08:22:12+01:00").toString());
|
||||
temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z"));
|
||||
temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12"));
|
||||
temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00"));
|
||||
temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]"));
|
||||
|
||||
session.save(temporalValues);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
|
||||
assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15"));
|
||||
assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18"));
|
||||
//assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00"));
|
||||
assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z"));
|
||||
assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12"));
|
||||
//assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00"));
|
||||
assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.hibernate.lob;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Session;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.lob.model.User;
|
||||
|
||||
public class LobUnitTest {
|
||||
|
||||
private Session session;
|
||||
|
||||
@Before
|
||||
public void init(){
|
||||
try {
|
||||
session = HibernateSessionUtil.getSessionFactory("hibernate.properties")
|
||||
.openSession();
|
||||
} catch (HibernateException | IOException e) {
|
||||
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void close(){
|
||||
if(session != null) session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){
|
||||
User user = new User();
|
||||
try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) {
|
||||
// Get Image file from the resource
|
||||
if(inputStream == null) fail("Unable to get resources");
|
||||
user.setId("1");
|
||||
user.setName("User");
|
||||
user.setPhoto(IOUtils.toByteArray(inputStream));
|
||||
|
||||
session.persist(user);
|
||||
} catch (IOException e) {
|
||||
fail("Unable to read input stream");
|
||||
}
|
||||
|
||||
User result = session.find(User.class, "1");
|
||||
|
||||
assertNotNull("Query result is null", result);
|
||||
assertEquals("User's name is invalid", user.getName(), result.getName() );
|
||||
assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) );
|
||||
}
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.dialect.H2Dialect
|
||||
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
|
||||
@@ -0,0 +1,25 @@
|
||||
create sequence hibernate_sequence start with 1 increment by 1;
|
||||
|
||||
create table Football_Player (
|
||||
id bigint not null,
|
||||
name varchar(255),
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
insert into
|
||||
Football_Player
|
||||
(name, id)
|
||||
values
|
||||
('Cristiano Ronaldo', next value for hibernate_sequence);
|
||||
|
||||
insert into
|
||||
Football_Player
|
||||
(name, id)
|
||||
values
|
||||
('Lionel Messi', next value for hibernate_sequence);
|
||||
|
||||
insert into
|
||||
Football_Player
|
||||
(name, id)
|
||||
values
|
||||
('Gigi Buffon', next value for hibernate_sequence);
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
Reference in New Issue
Block a user