Merge pull request #6 from eugenp/master

merge sync up
This commit is contained in:
vatsalgosar
2019-10-20 20:00:20 +05:30
committed by GitHub
parent db85c8f275
commit ade303a6de
20475 changed files with 1641579 additions and 0 deletions
@@ -0,0 +1,54 @@
package com.baeldung.jpa.basicannotation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class BasicAnnotationIntegrationTest {
private static EntityManager entityManager;
private static EntityManagerFactory entityManagerFactory;
@BeforeClass
public static void setup() {
entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
}
@Test
public void givenACourse_whenCourseNamePresent_shouldPersist() {
Course course = new Course();
course.setName("Computers");
entityManager.persist(course);
entityManager.flush();
entityManager.clear();
}
@Test(expected = PersistenceException.class)
public void givenACourse_whenCourseNameAbsent_shouldFail() {
Course course = new Course();
entityManager.persist(course);
entityManager.flush();
entityManager.clear();
}
@AfterClass
public static void destroy() {
if (entityManager != null) {
entityManager.close();
}
if (entityManagerFactory != null) {
entityManagerFactory.close();
}
}
}
@@ -0,0 +1,89 @@
package com.baeldung.jpa.entity;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class StudentEntityIntegrationTest {
private EntityManagerFactory emf;
private EntityManager em;
@Before
public void setup() {
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
em = emf.createEntityManager();
}
@Test
public void persistStudentThenRetrieveTheDetails() {
Student student = createStudentWithRelevantDetails();
persist(student);
clearThePersistenceContext();
List<Student> students = getStudentsFromTable();
checkAssertionsWith(students);
}
@After
public void destroy() {
if (em != null) {
em.close();
}
if (emf != null) {
emf.close();
}
}
private void clearThePersistenceContext() {
em.clear();
}
private void checkAssertionsWith(List<Student> students) {
assertEquals(1, students.size());
Student john = students.get(0);
assertEquals(1L, john.getId().longValue());
assertEquals(null, john.getAge());
assertEquals("John", john.getName());
}
private List<Student> getStudentsFromTable() {
String selectQuery = "SELECT student FROM Student student";
TypedQuery<Student> selectFromStudentTypedQuery = em.createQuery(selectQuery, Student.class);
List<Student> students = selectFromStudentTypedQuery.getResultList();
return students;
}
private void persist(Student student) {
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
}
private Student createStudentWithRelevantDetails() {
Student student = new Student();
student.setAge(20); // the 'age' field has been annotated with @Transient
student.setName("John");
Date date = getDate();
student.setBirthDate(date);
student.setGender(Gender.MALE);
return student;
}
private Date getDate() {
LocalDate localDate = LocalDate.of(2008, 7, 20);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
}
@@ -0,0 +1,68 @@
package com.baeldung.jpa.entitygraph.repo;
import com.baeldung.jpa.entitygraph.model.Comment;
import com.baeldung.jpa.entitygraph.model.Post;
import com.baeldung.jpa.entitygraph.model.User;
import org.hibernate.LazyInitializationException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class PostRepositoryIntegrationTest {
private static PostRepository postRepository = null;
@BeforeClass
public static void once() {
postRepository = new PostRepository();
}
@Test(expected = LazyInitializationException.class)
public void find() {
Post post = postRepository.find(1L);
assertNotNull(post.getUser());
String email = post.getUser().getEmail();
assertNull(email);
}
@Test
public void findWithEntityGraph() {
Post post = postRepository.findWithEntityGraph(1L);
assertNotNull(post.getUser());
String email = post.getUser().getEmail();
assertNotNull(email);
}
@Test(expected = LazyInitializationException.class)
public void findWithEntityGraph_Comment_Without_User() {
Post post = postRepository.findWithEntityGraph(1L);
assertNotNull(post.getUser());
String email = post.getUser().getEmail();
assertNotNull(email);
assertNotNull(post.getComments());
assertEquals(post.getComments().size(), 2);
Comment comment = post.getComments().get(0);
assertNotNull(comment);
User user = comment.getUser();
user.getEmail();
}
@Test
public void findWithEntityGraph2_Comment_With_User() {
Post post = postRepository.findWithEntityGraph2(1L);
assertNotNull(post.getComments());
assertEquals(post.getComments().size(), 2);
Comment comment = post.getComments().get(0);
assertNotNull(comment);
User user = comment.getUser();
assertNotNull(user);
assertEquals(user.getEmail(), "user2@test.com");
}
@AfterClass
public static void destroy() {
postRepository.clean();
}
}
@@ -0,0 +1,118 @@
package com.baeldung.jpa.enums;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArticleUnitTest {
private static EntityManager em;
private static EntityManagerFactory emFactory;
@BeforeClass
public static void setup() {
Map properties = new HashMap();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
emFactory = Persistence.createEntityManagerFactory("jpa-h2", properties);
em = emFactory.createEntityManager();
}
@Test
public void shouldPersistStatusEnumOrdinalValue() {
// given
Article article = new Article();
article.setId(1);
article.setTitle("ordinal title");
article.setStatus(Status.OPEN);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 1);
assertEquals(1, persistedArticle.getId());
assertEquals("ordinal title", persistedArticle.getTitle());
assertEquals(Status.OPEN, persistedArticle.getStatus());
}
@Test
public void shouldPersistTypeEnumStringValue() {
// given
Article article = new Article();
article.setId(2);
article.setTitle("string title");
article.setType(Type.EXTERNAL);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 2);
assertEquals(2, persistedArticle.getId());
assertEquals("string title", persistedArticle.getTitle());
assertEquals(Type.EXTERNAL, persistedArticle.getType());
}
@Test
public void shouldPersistPriorityIntValue() {
// given
Article article = new Article();
article.setId(3);
article.setTitle("callback title");
article.setPriority(Priority.HIGH);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 3);
assertEquals(3, persistedArticle.getId());
assertEquals("callback title", persistedArticle.getTitle());
assertEquals(Priority.HIGH, persistedArticle.getPriority());
}
@Test
public void shouldPersistCategoryEnumConvertedValue() {
// given
Article article = new Article();
article.setId(4);
article.setTitle("converted title");
article.setCategory(Category.MUSIC);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 4);
assertEquals(4, persistedArticle.getId());
assertEquals("converted title", persistedArticle.getTitle());
assertEquals(Category.MUSIC, persistedArticle.getCategory());
}
}
@@ -0,0 +1,118 @@
package com.baeldung.jpa.primarykeys;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.baeldung.jpa.primarykeys.Account;
import com.baeldung.jpa.primarykeys.AccountId;
import com.baeldung.jpa.primarykeys.Book;
import com.baeldung.jpa.primarykeys.BookId;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class CompositeKeysIntegrationTest {
private static final String SAVINGS_ACCOUNT = "Savings";
private static final String ACCOUNT_NUMBER = "JXSDF324234";
private static final String ENGLISH = "English";
private static final String WAR_AND_PEACE = "War and Peace";
private static EntityManagerFactory emf;
private static EntityManager em;
@BeforeClass
public static void setup() {
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
em = emf.createEntityManager();
}
@Test
public void persistBookWithCompositeKeyThenRetrieveDetails() {
Book warAndPeace = createBook();
persist(warAndPeace);
clearThePersistenceContext();
Book book = findBookByBookId();
verifyAssertionsWith(book);
}
@Test
public void persistAccountWithCompositeKeyThenRetrieveDetails() {
Account savingsAccount = createAccount();
persist(savingsAccount);
clearThePersistenceContext();
Account account = findAccountByAccountId();
verifyAssertionsWith(account);
}
@AfterClass
public static void destroy() {
if (em != null) {
em.close();
}
if (emf != null) {
emf.close();
}
}
private Account createAccount() {
Account savingsAccount = new Account();
savingsAccount.setAccountNumber(ACCOUNT_NUMBER);
savingsAccount.setAccountType(SAVINGS_ACCOUNT);
savingsAccount.setDescription("Savings account");
return savingsAccount;
}
private void verifyAssertionsWith(Account account) {
assertEquals(ACCOUNT_NUMBER, account.getAccountNumber());
assertEquals(SAVINGS_ACCOUNT, account.getAccountType());
}
private Account findAccountByAccountId() {
return em.find(Account.class, new AccountId(ACCOUNT_NUMBER, SAVINGS_ACCOUNT));
}
private void persist(Account account) {
em.getTransaction()
.begin();
em.persist(account);
em.getTransaction()
.commit();
}
private Book findBookByBookId() {
return em.find(Book.class, new BookId(WAR_AND_PEACE, ENGLISH));
}
private Book createBook() {
BookId bookId = new BookId(WAR_AND_PEACE, ENGLISH);
Book warAndPeace = new Book(bookId);
warAndPeace.setDescription("Novel and Historical Fiction");
return warAndPeace;
}
private void verifyAssertionsWith(Book book) {
assertNotNull(book);
assertNotNull(book.getBookId());
assertEquals(WAR_AND_PEACE, book.getBookId()
.getTitle());
assertEquals(ENGLISH, book.getBookId()
.getLanguage());
}
private void persist(Book book) {
em.getTransaction()
.begin();
em.persist(book);
em.getTransaction()
.commit();
}
private void clearThePersistenceContext() {
em.clear();
}
}
@@ -0,0 +1,70 @@
package com.baeldung.jpa.sqlresultsetmapping;
import static org.junit.Assert.*;
import org.junit.jupiter.api.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Collections;
import java.util.List;
public class SqlResultSetMappingUnitTest {
private static EntityManager em;
private static EntityManagerFactory emFactory;
@BeforeAll
public static void setup() {
emFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
em = emFactory.createEntityManager();
}
@Test
public void whenNamedQuery_thenColumnResult() {
List<Long> employeeIds = em.createNamedQuery("FridayEmployees").getResultList();
assertEquals(2, employeeIds.size());
}
@Test
public void whenNamedQuery_thenConstructorResult() {
List<ScheduledDay> scheduleDays = Collections.checkedList(em.createNamedQuery("Schedules", ScheduledDay.class).getResultList(), ScheduledDay.class);
assertEquals(2, scheduleDays.size());
assertTrue(scheduleDays.stream().allMatch(c -> c.getEmployeeId().longValue() == 3));
}
@Test
public void whenNamedQuery_thenSingleEntityResult() {
List<Employee> employees = Collections.checkedList(em.createNamedQuery("Employees").getResultList(), Employee.class);
assertEquals(3, employees.size());
assertTrue(employees.stream().allMatch(c -> c.getClass() == Employee.class));
}
@Test
public void whenNamedQuery_thenMultipleEntityResult() {
final Query query = em.createNativeQuery("SELECT e.id, e.name, d.id, d.employeeId, d.dayOfWeek "
+ " FROM employee e, schedule_days d "
+ " WHERE e.id = d.employeeId", "EmployeeScheduleResults");
List<Object[]> results = query.getResultList();
assertEquals(4, results.size());
assertTrue(results.get(0).length == 2);
Employee emp = (Employee) results.get(1)[0];
ScheduledDay day = (ScheduledDay) results.get(1)[1];
assertTrue(day.getEmployeeId() == emp.getId());
}
@AfterAll
public static void destroy() {
if (em != null) {
em.close();
}
if (emFactory != null) {
emFactory.close();
}
}
}
@@ -0,0 +1,76 @@
package com.baeldung.jpa.storedprocedure;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.ParameterMode;
import javax.persistence.Persistence;
import javax.persistence.StoredProcedureQuery;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.jpa.model.Car;
public class StoredProcedureLiveTest {
private static EntityManagerFactory factory = null;
private static EntityManager entityManager = null;
@BeforeClass
public static void init() {
factory = Persistence.createEntityManagerFactory("jpa-db");
entityManager = factory.createEntityManager();
}
@Before
public void setup() {
}
@Test
public void createCarTest() {
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
final Car car = new Car("Fiat Marea", 2015);
entityManager.persist(car);
transaction.commit();
} catch (final Exception e) {
System.out.println(e.getCause());
if (transaction.isActive()) {
transaction.rollback();
}
}
}
@Test
public void findCarsByYearNamedProcedure() {
final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure");
final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015);
storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}
@Test
public void findCarsByYearNoNamed() {
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
.setParameter(1, 2015);
storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}
@AfterClass
public static void destroy() {
if (entityManager != null) {
entityManager.close();
}
if (factory != null) {
factory.close();
}
}
}
@@ -0,0 +1,53 @@
package com.baeldung.jpa.stringcast;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.*;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SpringCastUnitTest {
private static EntityManager em;
private static EntityManagerFactory emFactory;
@BeforeClass
public static void setup() {
emFactory = Persistence.createEntityManagerFactory("jpa-h2");
em = emFactory.createEntityManager();
// insert an object into the db
Message message = new Message();
message.setText("text");
EntityTransaction tr = em.getTransaction();
tr.begin();
em.persist(message);
tr.commit();
}
@Test(expected = ClassCastException.class)
public void givenExecutorNoCastCheck_whenQueryReturnsOneColumn_thenClassCastThrown() {
List<String[]> results = QueryExecutor.executeNativeQueryNoCastCheck("select text from message", em);
// fails
for (String[] row : results) {
// do nothing
}
}
@Test
public void givenExecutorWithCastCheck_whenQueryReturnsOneColumn_thenNoClassCastThrown() {
List<String[]> results = QueryExecutor.executeNativeQueryWithCastCheck("select text from message", em);
assertEquals("text", results.get(0)[0]);
}
@Test
public void givenExecutorGeneric_whenQueryReturnsOneColumn_thenNoClassCastThrown() {
List<Message> results = QueryExecutor.executeNativeQueryGeneric("select text from message", "textQueryMapping", em);
assertEquals("text", results.get(0).getText());
}
}
@@ -0,0 +1,3 @@
INSERT INTO employee (1, "JOHN");
INSERT INTO employee (2, "MARY");
INSERT INTO employee (3, "FRANK");
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="jpa-db">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung" />
<property name="javax.persistence.jdbc.user" value="baeldung" />
<property name="javax.persistence.jdbc.password" value="YourPassword" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.stringcast.Message</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
@@ -0,0 +1,10 @@
INSERT INTO SCHEDULE_DAYS (1, 13, 21, 'FRIDAY');
INSERT INTO SCHEDULE_DAYS (2, 8, 4, 'SATURDAY');
INSERT INTO SCHEDULE_DAYS (3, 8, 4, 'FRIDAY');
-- private Long id;
-- private Long employeeId;
-- private Time in;
-- private Time out;
-- private DayOfWeek dayOfWeek;