Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu
2019-05-10 23:46:54 +03:00
committed by GitHub
2348 changed files with 46306 additions and 7323 deletions
+23 -8
View File
@@ -1,12 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<groupId>com.baeldung</groupId>
<artifactId>spring-data-jpa-2</artifactId>
<name>spring-data-jpa</name>
<name>spring-data-jpa</name>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
@@ -19,12 +20,26 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<dependency>
<groupId>net.ttddyy</groupId>
<artifactId>datasource-proxy</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,53 @@
package com.baeldung.batchinserts;
import java.lang.reflect.Method;
import javax.sql.DataSource;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
@Component
@Profile("batchinserts")
public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
if (bean instanceof DataSource) {
ProxyFactory factory = new ProxyFactory(bean);
factory.setProxyTargetClass(true);
factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean));
return factory.getProxy();
}
return bean;
}
private static class ProxyDataSourceInterceptor implements MethodInterceptor {
private final DataSource dataSource;
public ProxyDataSourceInterceptor(final DataSource dataSource) {
this.dataSource = ProxyDataSourceBuilder.create(dataSource).name("Batch-Insert-Logger").asJson().countQuery().logQueryToSysOut().build();
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
Method proxyMethod = ReflectionUtils.findMethod(dataSource.getClass(), invocation.getMethod().getName());
if (proxyMethod != null) {
return proxyMethod.invoke(dataSource, invocation.getArguments());
}
return invocation.proceed();
}
}
}
@@ -0,0 +1,45 @@
package com.baeldung.batchinserts.model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class School {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@OneToMany(mappedBy = "school")
private List<Student> students;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.batchinserts.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@ManyToOne
private School school;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
}
@@ -0,0 +1,35 @@
package com.baeldung.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean;
import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.baeldung.entity.Fruit;
@Configuration
public class JpaPopulators {
@Bean
public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception {
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") });
return factory;
}
@Bean
public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() {
Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
unmarshaller.setClassesToBeBound(Fruit.class);
UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean();
factory.setUnmarshaller(unmarshaller);
factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") });
return factory;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.datajpadelete.entity;
import javax.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne
private Category category;
public Book() {
}
public Book(String title) {
this.title = title;
}
public Book(String title, Category category) {
this.title = title;
this.category = category;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
@@ -0,0 +1,60 @@
package com.baeldung.datajpadelete.entity;
import javax.persistence.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Entity
public class Category {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books;
public Category() {
}
public Category(String name) {
this.name = name;
}
public Category(String name, Book... books) {
this.name = name;
this.books = Stream.of(books).collect(Collectors.toList());
this.books.forEach(x -> x.setCategory(this));
}
public Category(String name, List<Book> books) {
this.name = name;
this.books = books;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.datajpadelete.repository;
import com.baeldung.datajpadelete.entity.Book;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends CrudRepository<Book, Long> {
long deleteByTitle(String title);
@Modifying
@Query("delete from Book b where b.title=:title")
void deleteBooks(@Param("title") String title);
}
@@ -0,0 +1,9 @@
package com.baeldung.datajpadelete.repository;
import com.baeldung.datajpadelete.entity.Category;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoryRepository extends CrudRepository<Category, Long> {
}
@@ -0,0 +1,70 @@
package com.baeldung.derivedquery.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.ZonedDateTime;
@Table(name = "users")
@Entity
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private ZonedDateTime birthDate;
private Boolean active;
public User() {
}
public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) {
this.name = name;
this.age = age;
this.birthDate = birthDate;
this.active = active;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public ZonedDateTime getBirthDate() {
return birthDate;
}
public void setBirthDate(ZonedDateTime birthDate) {
this.birthDate = birthDate;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
@@ -0,0 +1,60 @@
package com.baeldung.derivedquery.repository;
import com.baeldung.derivedquery.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Integer> {
List<User> findByName(String name);
List<User> findByNameIs(String name);
List<User> findByNameEquals(String name);
List<User> findByNameIsNull();
List<User> findByNameNot(String name);
List<User> findByNameIsNot(String name);
List<User> findByNameStartingWith(String name);
List<User> findByNameEndingWith(String name);
List<User> findByNameContaining(String name);
List<User> findByNameLike(String name);
List<User> findByAgeLessThan(Integer age);
List<User> findByAgeLessThanEqual(Integer age);
List<User> findByAgeGreaterThan(Integer age);
List<User> findByAgeGreaterThanEqual(Integer age);
List<User> findByAgeBetween(Integer startAge, Integer endAge);
List<User> findByBirthDateAfter(ZonedDateTime birthDate);
List<User> findByBirthDateBefore(ZonedDateTime birthDate);
List<User> findByActiveTrue();
List<User> findByActiveFalse();
List<User> findByAgeIn(Collection<Integer> ages);
List<User> findByNameOrBirthDate(String name, ZonedDateTime birthDate);
List<User> findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active);
List<User> findByNameOrderByName(String name);
List<User> findByNameOrderByNameDesc(String name);
}
@@ -0,0 +1,71 @@
package com.baeldung.embeddable.model;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Company {
@Id
@GeneratedValue
private Integer id;
private String name;
private String address;
private String phone;
@Embedded
@AttributeOverrides(value = {
@AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")),
@AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name")),
@AttributeOverride( name = "phone", column = @Column(name = "contact_phone"))
})
private ContactPerson contactPerson;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public ContactPerson getContactPerson() {
return contactPerson;
}
public void setContactPerson(ContactPerson contactPerson) {
this.contactPerson = contactPerson;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.embeddable.model;
import javax.persistence.Embeddable;
@Embeddable
public class ContactPerson {
private String firstName;
private String lastName;
private String phone;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.embeddable.repositories;
import com.baeldung.embeddable.model.Company;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface CompanyRepository extends JpaRepository<Company, Integer> {
List<Company> findByContactPersonFirstName(String firstName);
@Query("SELECT C FROM Company C WHERE C.contactPerson.firstName = ?1")
List<Company> findByContactPersonFirstNameWithJPQL(String firstName);
@Query(value = "SELECT * FROM company WHERE contact_first_name = ?1", nativeQuery = true)
List<Company> findByContactPersonFirstNameWithNativeQuery(String firstName);
}
@@ -2,7 +2,9 @@ package com.baeldung.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@Entity
public class Fruit {
@@ -0,0 +1,43 @@
package com.baeldung.entitygraph.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Characteristic {
@Id
private Long id;
private String type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Item item;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.entitygraph.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.OneToMany;
@Entity
@NamedEntityGraph(name = "Item.characteristics",
attributeNodes = @NamedAttributeNode("characteristics")
)
public class Item {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "item")
private List<Characteristic> characteristics = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(List<Characteristic> characteristics) {
this.characteristics = characteristics;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.entitygraph.repository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.entitygraph.model.Characteristic;
public interface CharacteristicsRepository extends JpaRepository<Characteristic, Long> {
@EntityGraph(attributePaths = {"item"})
Characteristic findByType(String type);
}
@@ -0,0 +1,13 @@
package com.baeldung.entitygraph.repository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.entitygraph.model.Item;
public interface ItemRepository extends JpaRepository<Item, Long> {
@EntityGraph(value = "Item.characteristics", type = EntityGraphType.FETCH)
Item findByName(String name);
}
@@ -0,0 +1,57 @@
package com.baeldung.projection.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class Address {
@Id
private Long id;
@OneToOne
private Person person;
private String state;
private String city;
private String street;
private String zipCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
@@ -0,0 +1,47 @@
package com.baeldung.projection.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class Person {
@Id
private Long id;
private String firstName;
private String lastName;
@OneToOne(mappedBy = "person")
private Address address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@@ -0,0 +1,11 @@
package com.baeldung.projection.repository;
import com.baeldung.projection.view.AddressView;
import com.baeldung.projection.model.Address;
import org.springframework.data.repository.Repository;
import java.util.List;
public interface AddressRepository extends Repository<Address, Long> {
List<AddressView> getAddressByState(String state);
}
@@ -0,0 +1,14 @@
package com.baeldung.projection.repository;
import com.baeldung.projection.model.Person;
import com.baeldung.projection.view.PersonDto;
import com.baeldung.projection.view.PersonView;
import org.springframework.data.repository.Repository;
public interface PersonRepository extends Repository<Person, Long> {
PersonView findByLastName(String lastName);
PersonDto findByFirstName(String firstName);
<T> T findByLastName(String lastName, Class<T> type);
}
@@ -0,0 +1,7 @@
package com.baeldung.projection.view;
public interface AddressView {
String getZipCode();
PersonView getPerson();
}
@@ -0,0 +1,34 @@
package com.baeldung.projection.view;
import java.util.Objects;
public class PersonDto {
private final String firstName;
private final String lastName;
public PersonDto(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonDto personDto = (PersonDto) o;
return Objects.equals(firstName, personDto.firstName) && Objects.equals(lastName, personDto.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.projection.view;
import org.springframework.beans.factory.annotation.Value;
public interface PersonView {
String getFirstName();
String getLastName();
@Value("#{target.firstName + ' ' + target.lastName}")
String getFullName();
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<fruit>
<id>1</id>
<name>apple</name>
<color>red</color>
</fruit>
@@ -0,0 +1,6 @@
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.jdbc.batch_size=5
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.batch_versioned_data=true
@@ -0,0 +1,14 @@
[
{
"_class": "com.baeldung.entity.Fruit",
"name": "apple",
"color": "red",
"id": 1
},
{
"_class": "com.baeldung.entity.Fruit",
"name": "guava",
"color": "green",
"id": 2
}
]
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<fruit>
<id>2</id>
<name>guava</name>
<color>green</color>
</fruit>
@@ -0,0 +1,94 @@
package com.baeldung.batchinserts;
import static com.baeldung.batchinserts.TestObjectHelper.createSchool;
import static com.baeldung.batchinserts.TestObjectHelper.createStudent;
import com.baeldung.batchinserts.model.School;
import com.baeldung.batchinserts.model.Student;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@ActiveProfiles("batchinserts")
public class JpaBatchInsertsIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
private static final int BATCH_SIZE = 5;
@Transactional
@Test
public void whenInsertingSingleTypeOfEntity_thenCreatesSingleBatch() {
for (int i = 0; i < 10; i++) {
School school = createSchool(i);
entityManager.persist(school);
}
}
@Transactional
@Test
public void whenFlushingAfterBatch_ThenClearsMemory() {
for (int i = 0; i < 10; i++) {
if (i > 0 && i % BATCH_SIZE == 0) {
entityManager.flush();
entityManager.clear();
}
School school = createSchool(i);
entityManager.persist(school);
}
}
@Transactional
@Test
public void whenThereAreMultipleEntities_ThenCreatesNewBatch() {
for (int i = 0; i < 10; i++) {
if (i > 0 && i % BATCH_SIZE == 0) {
entityManager.flush();
entityManager.clear();
}
School school = createSchool(i);
entityManager.persist(school);
Student firstStudent = createStudent(school);
Student secondStudent = createStudent(school);
entityManager.persist(firstStudent);
entityManager.persist(secondStudent);
}
}
@Transactional
@Test
public void whenUpdatingEntities_thenCreatesBatch() {
for (int i = 0; i < 10; i++) {
School school = createSchool(i);
entityManager.persist(school);
}
entityManager.flush();
TypedQuery<School> schoolQuery = entityManager.createQuery("SELECT s from School s", School.class);
List<School> allSchools = schoolQuery.getResultList();
for (School school : allSchools) {
school.setName("Updated_" + school.getName());
}
}
@After
public void tearDown() {
entityManager.flush();
}
}
@@ -0,0 +1,39 @@
package com.baeldung.batchinserts;
import static com.baeldung.batchinserts.TestObjectHelper.createSchool;
import com.baeldung.batchinserts.model.School;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@ActiveProfiles("batchinserts")
@TestPropertySource(properties = "spring.jpa.properties.hibernate.jdbc.batch_size=-1")
public class JpaNoBatchInsertsIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Test
public void whenNotConfigured_ThenSendsInsertsSeparately() {
for (int i = 0; i < 10; i++) {
School school = createSchool(i);
entityManager.persist(school);
}
}
@After
public void tearDown() {
entityManager.flush();
}
}
@@ -0,0 +1,20 @@
package com.baeldung.batchinserts;
import com.baeldung.batchinserts.model.School;
import com.baeldung.batchinserts.model.Student;
public class TestObjectHelper {
public static School createSchool(int nameIdentifier) {
School school = new School();
school.setName("School" + (nameIdentifier + 1));
return school;
}
public static Student createStudent(School school) {
Student student = new Student();
student.setName("Student-" + school.getName());
student.setSchool(school);
return student;
}
}
@@ -0,0 +1,72 @@
package com.baeldung.datajpadelete;
import com.baeldung.Application;
import com.baeldung.datajpadelete.entity.Book;
import com.baeldung.datajpadelete.repository.BookRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class DeleteFromRepositoryUnitTest {
@Autowired
private BookRepository repository;
Book book1;
Book book2;
@Before
public void setup() {
book1 = new Book("The Hobbit");
book2 = new Book("All Quiet on the Western Front");
repository.saveAll(Arrays.asList(book1, book2));
}
@After
public void teardown() {
repository.deleteAll();
}
@Test
public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() {
repository.deleteById(book1.getId());
assertThat(repository.count() == 1).isTrue();
}
@Test
public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() {
repository.deleteAll();
assertThat(repository.count() == 0).isTrue();
}
@Test
@Transactional
public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() {
repository.deleteByTitle("The Hobbit");
assertThat(repository.count() == 1).isTrue();
}
@Test
@Transactional
public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() {
repository.deleteBooks("The Hobbit");
assertThat(repository.count() == 1).isTrue();
}
}
@@ -0,0 +1,60 @@
package com.baeldung.datajpadelete;
import com.baeldung.Application;
import com.baeldung.datajpadelete.entity.Book;
import com.baeldung.datajpadelete.entity.Category;
import com.baeldung.datajpadelete.repository.BookRepository;
import com.baeldung.datajpadelete.repository.CategoryRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class DeleteInRelationshipsUnitTest {
@Autowired
private BookRepository bookRepository;
@Autowired
private CategoryRepository categoryRepository;
@Before
public void setup() {
Book book1 = new Book("The Hobbit");
Category category1 = new Category("Cat1", book1);
categoryRepository.save(category1);
Book book2 = new Book("All Quiet on the Western Front");
Category category2 = new Category("Cat2", book2);
categoryRepository.save(category2);
}
@After
public void teardown() {
bookRepository.deleteAll();
categoryRepository.deleteAll();
}
@Test
public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() {
categoryRepository.deleteAll();
assertThat(bookRepository.count() == 0).isTrue();
assertThat(categoryRepository.count() == 0).isTrue();
}
@Test
public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() {
bookRepository.deleteAll();
assertThat(bookRepository.count() == 0).isTrue();
assertThat(categoryRepository.count() == 2).isTrue();
}
}
@@ -0,0 +1,172 @@
package com.baeldung.derivedquery.repository;
import com.baeldung.Application;
import com.baeldung.derivedquery.entity.User;
import com.baeldung.derivedquery.repository.UserRepository;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class UserRepositoryTest {
private static final String USER_NAME_ADAM = "Adam";
private static final String USER_NAME_EVE = "Eve";
private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now();
@Autowired
private UserRepository userRepository;
@Before
public void setUp() {
User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true);
User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false);
User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true);
User user4 = new User(null, 30, BIRTHDATE, false);
userRepository.saveAll(Arrays.asList(user1, user2, user3, user4));
}
@After
public void tearDown() {
userRepository.deleteAll();
}
@Test
public void whenFindByName_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size());
}
@Test
public void whenFindByNameIsNull_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameIsNull().size());
}
@Test
public void whenFindByNameNot_thenReturnsCorrectResult() {
assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName());
}
@Test
public void whenFindByNameStartingWith_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByNameStartingWith("A").size());
}
@Test
public void whenFindByNameEndingWith_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameEndingWith("e").size());
}
@Test
public void whenByNameContaining_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameContaining("v").size());
}
@Test
public void whenByNameLike_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByNameEndingWith("%d%m").size());
}
@Test
public void whenByAgeLessThan_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByAgeLessThan(25).size());
}
@Test
public void whenByAgeLessThanEqual_thenReturnsCorrectResult() {
assertEquals(3, userRepository.findByAgeLessThanEqual(25).size());
}
@Test
public void whenByAgeGreaterThan_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByAgeGreaterThan(25).size());
}
@Test
public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size());
}
@Test
public void whenByAgeBetween_thenReturnsCorrectResult() {
assertEquals(4, userRepository.findByAgeBetween(20, 30).size());
}
@Test
public void whenByBirthDateAfter_thenReturnsCorrectResult() {
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size());
}
@Test
public void whenByBirthDateBefore_thenReturnsCorrectResult() {
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size());
}
@Test
public void whenByActiveTrue_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByActiveTrue().size());
}
@Test
public void whenByActiveFalse_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByActiveFalse().size());
}
@Test
public void whenByAgeIn_thenReturnsCorrectResult() {
final List<Integer> ages = Arrays.asList(20, 25);
assertEquals(3, userRepository.findByAgeIn(ages).size());
}
@Test
public void whenByNameOrBirthDate() {
assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size());
}
@Test
public void whenByNameOrBirthDateAndActive() {
assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size());
}
@Test
public void whenByNameOrderByName() {
assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size());
}
}
@@ -0,0 +1,125 @@
package com.baeldung.embeddable;
import com.baeldung.Application;
import com.baeldung.embeddable.model.Company;
import com.baeldung.embeddable.model.ContactPerson;
import com.baeldung.embeddable.repositories.CompanyRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class EmbeddableIntegrationTest {
@Autowired
private CompanyRepository companyRepository;
@Test
@Transactional
public void whenInsertingCompany_thenEmbeddedContactPersonDetailsAreMapped() {
ContactPerson contactPerson = new ContactPerson();
contactPerson.setFirstName("First");
contactPerson.setLastName("Last");
contactPerson.setPhone("123-456-789");
Company company = new Company();
company.setName("Company");
company.setAddress("1st street");
company.setPhone("987-654-321");
company.setContactPerson(contactPerson);
companyRepository.save(company);
Company result = companyRepository.getOne(company.getId());
assertEquals("Company", result.getName());
assertEquals("1st street", result.getAddress());
assertEquals("987-654-321", result.getPhone());
assertEquals("First", result.getContactPerson().getFirstName());
assertEquals("Last", result.getContactPerson().getLastName());
assertEquals("123-456-789", result.getContactPerson().getPhone());
}
@Test
@Transactional
public void whenFindingCompanyByContactPersonAttribute_thenCompanyIsReturnedProperly() {
ContactPerson contactPerson = new ContactPerson();
contactPerson.setFirstName("Name");
contactPerson.setLastName("Last");
contactPerson.setPhone("123-456-789");
Company company = new Company();
company.setName("Company");
company.setAddress("1st street");
company.setPhone("987-654-321");
company.setContactPerson(contactPerson);
companyRepository.save(company);
List<Company> result = companyRepository.findByContactPersonFirstName("Name");
assertEquals(1, result.size());
result = companyRepository.findByContactPersonFirstName("FirstName");
assertEquals(0, result.size());
}
@Test
@Transactional
public void whenFindingCompanyByContactPersonAttributeWithJPQL_thenCompanyIsReturnedProperly() {
ContactPerson contactPerson = new ContactPerson();
contactPerson.setFirstName("@QueryName");
contactPerson.setLastName("Last");
contactPerson.setPhone("123-456-789");
Company company = new Company();
company.setName("Company");
company.setAddress("1st street");
company.setPhone("987-654-321");
company.setContactPerson(contactPerson);
companyRepository.save(company);
List<Company> result = companyRepository.findByContactPersonFirstNameWithJPQL("@QueryName");
assertEquals(1, result.size());
result = companyRepository.findByContactPersonFirstNameWithJPQL("FirstName");
assertEquals(0, result.size());
}
@Test
@Transactional
public void whenFindingCompanyByContactPersonAttributeWithNativeQuery_thenCompanyIsReturnedProperly() {
ContactPerson contactPerson = new ContactPerson();
contactPerson.setFirstName("NativeQueryName");
contactPerson.setLastName("Last");
contactPerson.setPhone("123-456-789");
Company company = new Company();
company.setName("Company");
company.setAddress("1st street");
company.setPhone("987-654-321");
company.setContactPerson(contactPerson);
companyRepository.save(company);
List<Company> result = companyRepository.findByContactPersonFirstNameWithNativeQuery("NativeQueryName");
assertEquals(1, result.size());
result = companyRepository.findByContactPersonFirstNameWithNativeQuery("FirstName");
assertEquals(0, result.size());
}
}
@@ -0,0 +1,39 @@
package com.baeldung.entitygraph;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.entitygraph.model.Characteristic;
import com.baeldung.entitygraph.model.Item;
import com.baeldung.entitygraph.repository.CharacteristicsRepository;
import com.baeldung.entitygraph.repository.ItemRepository;
@DataJpaTest
@RunWith(SpringRunner.class)
@Sql(scripts = "/entitygraph-data.sql")
public class EntityGraphIntegrationTest {
@Autowired
private ItemRepository itemRepo;
@Autowired
private CharacteristicsRepository characteristicsRepo;
@Test
public void givenEntityGraph_whenCalled_shouldRetrunDefinedFields() {
Item item = itemRepo.findByName("Table");
assertThat(item.getId()).isEqualTo(1L);
}
@Test
public void givenAdhocEntityGraph_whenCalled_shouldRetrunDefinedFields() {
Characteristic characteristic = characteristicsRepo.findByType("Rigid");
assertThat(characteristic.getId()).isEqualTo(1L);
}
}
@@ -0,0 +1,63 @@
package com.baeldung.projection;
import com.baeldung.projection.model.Person;
import com.baeldung.projection.repository.AddressRepository;
import com.baeldung.projection.repository.PersonRepository;
import com.baeldung.projection.view.AddressView;
import com.baeldung.projection.view.PersonDto;
import com.baeldung.projection.view.PersonView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
@DataJpaTest
@RunWith(SpringRunner.class)
@Sql(scripts = "/projection-insert-data.sql")
@Sql(scripts = "/projection-clean-up-data.sql", executionPhase = AFTER_TEST_METHOD)
public class JpaProjectionIntegrationTest {
@Autowired
private AddressRepository addressRepository;
@Autowired
private PersonRepository personRepository;
@Test
public void whenUsingClosedProjections_thenViewWithRequiredPropertiesIsReturned() {
AddressView addressView = addressRepository.getAddressByState("CA").get(0);
assertThat(addressView.getZipCode()).isEqualTo("90001");
PersonView personView = addressView.getPerson();
assertThat(personView.getFirstName()).isEqualTo("John");
assertThat(personView.getLastName()).isEqualTo("Doe");
}
@Test
public void whenUsingOpenProjections_thenViewWithRequiredPropertiesIsReturned() {
PersonView personView = personRepository.findByLastName("Doe");
assertThat(personView.getFullName()).isEqualTo("John Doe");
}
@Test
public void whenUsingClassBasedProjections_thenDtoWithRequiredPropertiesIsReturned() {
PersonDto personDto = personRepository.findByFirstName("John");
assertThat(personDto.getFirstName()).isEqualTo("John");
assertThat(personDto.getLastName()).isEqualTo("Doe");
}
@Test
public void whenUsingDynamicProjections_thenObjectWithRequiredPropertiesIsReturned() {
Person person = personRepository.findByLastName("Doe", Person.class);
PersonView personView = personRepository.findByLastName("Doe", PersonView.class);
PersonDto personDto = personRepository.findByLastName("Doe", PersonDto.class);
assertThat(person.getFirstName()).isEqualTo("John");
assertThat(personView.getFirstName()).isEqualTo("John");
assertThat(personDto.getFirstName()).isEqualTo("John");
}
}
@@ -0,0 +1,38 @@
package com.baeldung.repository;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.entity.Fruit;
@RunWith(SpringRunner.class)
@SpringBootTest
public class FruitPopulatorTest {
@Autowired
private FruitRepository fruitRepository;
@Test
public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() {
List<Fruit> fruits = fruitRepository.findAll();
assertEquals("record count is not matching", 2, fruits.size());
fruits.forEach(fruit -> {
if (1 == fruit.getId()) {
assertEquals("apple", fruit.getName());
assertEquals("red", fruit.getColor());
} else if (2 == fruit.getId()) {
assertEquals("guava", fruit.getName());
assertEquals("green", fruit.getColor());
}
});
}
}
@@ -0,0 +1,7 @@
INSERT INTO Item(id,name) VALUES (1,'Table');
INSERT INTO Item(id,name) VALUES (2,'Bottle');
INSERT INTO Characteristic(id,item_id, type) VALUES (1,1,'Rigid');
INSERT INTO Characteristic(id,item_id,type) VALUES (2,1,'Big');
INSERT INTO Characteristic(id,item_id,type) VALUES (3,2,'Fragile');
INSERT INTO Characteristic(id,item_id,type) VALUES (4,2,'Small');
@@ -0,0 +1,2 @@
DELETE FROM address;
DELETE FROM person;
@@ -0,0 +1,2 @@
INSERT INTO person(id,first_name,last_name) VALUES (1,'John','Doe');
INSERT INTO address(id,person_id,state,city,street,zip_code) VALUES (1,1,'CA', 'Los Angeles', 'Standford Ave', '90001');