New unit test format

This commit is contained in:
Nick
2019-08-30 21:11:18 +01:00
parent db85c8f275
commit 6cd385e4c0
19972 changed files with 1626600 additions and 0 deletions
@@ -0,0 +1,15 @@
### Relevant Articles:
- [Spring Data JPA Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
- [JPA Join Types](https://www.baeldung.com/jpa-join-types)
- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries)
- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query)
- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators)
- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters)
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable)
- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete)
- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs)
- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update)
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries)
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)
@@ -0,0 +1,49 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-data-jpa-2</artifactId>
<name>spring-data-jpa</name>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>net.ttddyy</groupId>
<artifactId>datasource-proxy</artifactId>
<version>${datasource-proxy.version}</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>
<properties>
<datasource-proxy.version>1.4.1</datasource-proxy.version>
</properties>
</project>
@@ -0,0 +1,13 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -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);
}
@@ -0,0 +1,37 @@
package com.baeldung.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue
private long id;
private String name;
private String email;
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private Long id;
private String name;
public Employee() {
}
public Employee(Long id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@Entity
public class Fruit {
@Id
private long id;
private String name;
private String color;
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 String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
@@ -0,0 +1,78 @@
package com.baeldung.entity;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class Passenger {
@Id
@GeneratedValue
@Column(nullable = false)
private Long id;
@Basic(optional = false)
@Column(nullable = false)
private String firstName;
@Basic(optional = false)
@Column(nullable = false)
private String lastName;
private Passenger(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public static Passenger from(String firstName, String lastName) {
return new Passenger(firstName, lastName);
}
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;
}
@Override
public String toString() {
return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Passenger passenger = (Passenger) o;
return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
}
@@ -0,0 +1,75 @@
package com.baeldung.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.time.LocalDateTime;
@Entity
public class Song {
@Id private long id;
private String name;
@Column(name = "length_in_seconds")
private int lengthInSeconds;
private String compositor;
private String singer;
private LocalDateTime released;
private String genre;
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 int getLengthInSeconds() {
return lengthInSeconds;
}
public void setLengthInSeconds(int lengthInSeconds) {
this.lengthInSeconds = lengthInSeconds;
}
public String getCompositor() {
return compositor;
}
public void setCompositor(String compositor) {
this.compositor = compositor;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
public LocalDateTime getReleased() {
return released;
}
public void setReleased(LocalDateTime released) {
this.released = released;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
}
@@ -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,48 @@
package com.baeldung.exists;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author paullatzelsperger
* @since 2019-03-20
*/
@Entity
public class Car {
@Id
@GeneratedValue
private int id;
private Integer power;
private String model;
Car() {
}
public Car(int power, String model) {
this.power = power;
this.model = model;
}
public Integer getPower() {
return power;
}
public void setPower(Integer power) {
this.power = power;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getId() {
return id;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.exists;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* @author paullatzelsperger
* @since 2019-03-20
*/
@Repository
public interface CarRepository extends JpaRepository<Car, Integer> {
boolean existsCarByPower(int power);
boolean existsCarByModel(String model);
@Query("select case when count(c)> 0 then true else false end from Car c where c.model = :model")
boolean existsCarExactCustomQuery(@Param("model") String model);
@Query("select case when count(c)> 0 then true else false end from Car c where lower(c.model) like lower(:model)")
boolean existsCarLikeCustomQuery(@Param("model") String model);
}
@@ -0,0 +1,45 @@
package com.baeldung.joins.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 Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
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<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
@@ -0,0 +1,69 @@
package com.baeldung.joins.model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "joins_employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private int age;
@ManyToOne
private Department department;
@OneToMany(mappedBy = "employee")
private List<Phone> phones;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.joins.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Phone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String number;
@ManyToOne
private Employee employee;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.like.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String title;
private String director;
private String rating;
private int duration;
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 String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.like.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import com.baeldung.like.model.Movie;
public interface MovieRepository extends CrudRepository<Movie, Long> {
List<Movie> findByTitleContaining(String title);
List<Movie> findByTitleLike(String title);
List<Movie> findByTitleContains(String title);
List<Movie> findByTitleIsContaining(String title);
List<Movie> findByRatingStartsWith(String rating);
List<Movie> findByDirectorEndsWith(String director);
List<Movie> findByTitleContainingIgnoreCase(String title);
List<Movie> findByRatingNotContaining(String rating);
List<Movie> findByDirectorNotLike(String director);
@Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%")
List<Movie> searchByTitleLike(@Param("title") String title);
@Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%")
List<Movie> searchByRatingStartsWith(String rating);
//Escaping works in SpringBoot >= 2.4.1
//@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}")
@Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}")
List<Movie> searchByDirectorEndsWith(String director);
}
@@ -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,19 @@
package com.baeldung.repository;
import com.baeldung.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByName(String name);
List<Customer> findByNameAndEmail(String name, String email);
@Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)")
List<Customer> findCustomerByNameAndEmail(@Param("name") String name, @Param("email") String email);
}
@@ -0,0 +1,9 @@
package com.baeldung.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
@@ -0,0 +1,27 @@
package com.baeldung.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.baeldung.entity.Fruit;
@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
Long deleteByName(String name);
List<Fruit> deleteByColor(String color);
Long removeByName(String name);
List<Fruit> removeByColor(String color);
@Modifying
@Query("delete from Fruit f where f.name=:name or f.color=:color")
List<Fruit> deleteFruits(@Param("name") String name, @Param("color") String color);
}
@@ -0,0 +1,14 @@
package com.baeldung.repository;
import com.baeldung.entity.Passenger;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
interface PassengerRepository extends JpaRepository<Passenger, Long> {
List<Passenger> findByFirstNameIgnoreCase(String firstName);
}
@@ -0,0 +1,21 @@
package com.baeldung.repository;
import com.baeldung.entity.Song;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface SongRepository extends JpaRepository<Song, Long> {
List<Song> findByNameLike(String name);
List<Song> findByNameNotLike(String name);
List<Song> findByNameStartingWith(String startingWith);
List<Song> findByNameEndingWith(String endingWith);
List<Song> findBySingerContaining(String singer);
}
@@ -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 @@
spring.datasource.data=classpath:db/import_joins.sql
@@ -0,0 +1 @@
spring.jpa.show-sql=true
@@ -0,0 +1,13 @@
INSERT INTO department (id, name) VALUES (1, 'Infra');
INSERT INTO department (id, name) VALUES (2, 'Accounting');
INSERT INTO department (id, name) VALUES (3, 'Management');
INSERT INTO joins_employee (id, name, age, department_id) VALUES (1, 'Baeldung', '35', 1);
INSERT INTO joins_employee (id, name, age, department_id) VALUES (2, 'John', '35', 2);
INSERT INTO joins_employee (id, name, age, department_id) VALUES (3, 'Jane', '35', 2);
INSERT INTO phone (id, number, employee_id) VALUES (1, '111', 1);
INSERT INTO phone (id, number, employee_id) VALUES (2, '222', 1);
INSERT INTO phone (id, number, employee_id) VALUES (3, '333', 1);
COMMIT;
@@ -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()).isEqualTo(1);
}
@Test
public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() {
repository.deleteAll();
assertThat(repository.count()).isEqualTo(0);
}
@Test
@Transactional
public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() {
long deletedRecords = repository.deleteByTitle("The Hobbit");
assertThat(deletedRecords).isEqualTo(1);
}
@Test
@Transactional
public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() {
repository.deleteBooks("The Hobbit");
assertThat(repository.count()).isEqualTo(1);
}
}
@@ -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()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(0);
}
@Test
public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() {
bookRepository.deleteAll();
assertThat(bookRepository.count()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(2);
}
}
@@ -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,87 @@
package com.baeldung.exists;
import com.baeldung.Application;
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.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.ignoreCase;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class CarRepositoryIntegrationTest {
@Autowired
private CarRepository repository;
private int searchId;
@Before
public void setup() {
List<Car> cars = repository.saveAll(Arrays.asList(new Car(200, "BMW"), new Car(300, "Audi")));
searchId = cars.get(0).getId();
}
@After
public void teardown() {
repository.deleteAll();
}
@Test
public void whenIdIsCorrect_thenExistsShouldReturnTrue() {
assertThat(repository.existsById(searchId)).isTrue();
}
@Test
public void givenExample_whenExists_thenIsTrue() {
ExampleMatcher modelMatcher = ExampleMatcher.matching()
.withIgnorePaths("id") // must explicitly ignore -> PK
.withMatcher("model", ignoreCase());
Car probe = new Car();
probe.setModel("bmw");
Example<Car> example = Example.of(probe, modelMatcher);
assertThat(repository.exists(example)).isTrue();
}
@Test
public void givenPower_whenExists_thenIsFalse() {
assertThat(repository.existsCarByPower(200)).isTrue();
assertThat(repository.existsCarByPower(800)).isFalse();
}
@Test
public void existsByDerivedQuery_byModel() {
assertThat(repository.existsCarByModel("Audi")).isTrue();
assertThat(repository.existsCarByModel("audi")).isFalse();
assertThat(repository.existsCarByModel("AUDI")).isFalse();
assertThat(repository.existsCarByModel("")).isFalse();
}
@Test
public void givenModelName_whenExistsExact_thenIsTrue() {
assertThat(repository.existsCarExactCustomQuery("BMW")).isTrue();
assertThat(repository.existsCarExactCustomQuery("Bmw")).isFalse();
assertThat(repository.existsCarExactCustomQuery("bmw")).isFalse();
assertThat(repository.existsCarExactCustomQuery("")).isFalse();
}
@Test
public void givenModelName_whenExistsLike_thenIsTrue() {
assertThat(repository.existsCarLikeCustomQuery("BMW")).isTrue();
assertThat(repository.existsCarLikeCustomQuery("Bmw")).isTrue();
assertThat(repository.existsCarLikeCustomQuery("bmw")).isTrue();
assertThat(repository.existsCarLikeCustomQuery("")).isFalse();
}
}
@@ -0,0 +1,142 @@
package com.baeldung.joins;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.joins.model.Department;
import com.baeldung.joins.model.Phone;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("joins")
public class JpaJoinsIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Test
public void whenPathExpressionIsUsedForSingleValuedAssociation_thenCreatesImplicitInnerJoin() {
TypedQuery<Department> query = entityManager.createQuery("SELECT e.department FROM Employee e", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(3);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Accounting");
}
@Test
public void whenJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() {
TypedQuery<Department> query = entityManager.createQuery("SELECT d FROM Employee e JOIN e.department d", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(3);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Accounting");
}
@Test
public void whenInnerJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() {
TypedQuery<Department> query = entityManager.createQuery("SELECT d FROM Employee e INNER JOIN e.department d", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(3);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Accounting");
}
@Test
public void whenEntitiesAreListedInFromAndMatchedInWhere_ThenCreatesJoin() {
TypedQuery<Department> query = entityManager.createQuery("SELECT d FROM Employee e, Department d WHERE e.department = d", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(3);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Accounting");
}
@Test
public void whenEntitiesAreListedInFrom_ThenCreatesCartesianProduct() {
TypedQuery<Department> query = entityManager.createQuery("SELECT d FROM Employee e, Department d", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(9);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Management", "Infra", "Accounting", "Management", "Infra", "Accounting", "Management");
}
@Test
public void whenCollectionValuedAssociationIsJoined_ThenCanSelect() {
TypedQuery<Phone> query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.phones ph WHERE ph LIKE '1%'", Phone.class);
List<Phone> resultList = query.getResultList();
assertThat(resultList).hasSize(1);
}
@Test
public void whenMultipleEntitiesAreListedWithJoin_ThenCreatesMultipleJoins() {
TypedQuery<Phone> query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.department d JOIN e.phones ph WHERE d.name IS NOT NULL", Phone.class);
List<Phone> resultList = query.getResultList();
assertThat(resultList).hasSize(3);
assertThat(resultList).extracting("number")
.containsOnly("111", "222", "333");
}
@Test
public void whenLeftKeywordIsSpecified_thenCreatesOuterJoinAndIncludesNonMatched() {
TypedQuery<Department> query = entityManager.createQuery("SELECT DISTINCT d FROM Department d LEFT JOIN d.employees e", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(3);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Management");
}
@Test
public void whenFetchKeywordIsSpecified_ThenCreatesFetchJoin() {
TypedQuery<Department> query = entityManager.createQuery("SELECT d FROM Department d JOIN FETCH d.employees", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(3);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Accounting");
}
@Test
public void whenLeftAndFetchKeywordsAreSpecified_ThenCreatesOuterFetchJoin() {
TypedQuery<Department> query = entityManager.createQuery("SELECT d FROM Department d LEFT JOIN FETCH d.employees", Department.class);
List<Department> resultList = query.getResultList();
assertThat(resultList).hasSize(4);
assertThat(resultList).extracting("name")
.containsOnly("Infra", "Accounting", "Accounting", "Management");
}
@Test
public void whenCollectionValuedAssociationIsSpecifiedInSelect_ThenReturnsCollections() {
TypedQuery<Collection> query = entityManager.createQuery("SELECT e.phones FROM Employee e", Collection.class);
List<Collection> resultList = query.getResultList();
assertThat(resultList).extracting("number").containsOnly("111", "222", "333");
}
}
@@ -0,0 +1,88 @@
package com.baeldung.like;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
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.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.like.model.Movie;
import com.baeldung.like.repository.MovieRepository;
@RunWith(SpringRunner.class)
@SpringBootTest
@Sql(scripts = { "/test-movie-data.sql" })
@Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD)
public class MovieRepositoryIntegrationTest {
@Autowired
private MovieRepository movieRepository;
@Test
public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByTitleContaining("in");
assertEquals(3, results.size());
results = movieRepository.findByTitleLike("%in%");
assertEquals(3, results.size());
results = movieRepository.findByTitleIsContaining("in");
assertEquals(3, results.size());
results = movieRepository.findByTitleContains("in");
assertEquals(3, results.size());
}
@Test
public void givenStartOfRating_WhenFindByRatingStartsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByRatingStartsWith("PG");
assertEquals(6, results.size());
}
@Test
public void givenLastName_WhenFindByDirectorEndsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByDirectorEndsWith("Burton");
assertEquals(1, results.size());
}
@Test
public void givenPartialTitle_WhenFindByTitleContainingIgnoreCase_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByTitleContainingIgnoreCase("the");
assertEquals(2, results.size());
}
@Test
public void givenPartialTitle_WhenSearchByTitleLike_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByTitleLike("in");
assertEquals(3, results.size());
}
@Test
public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByRatingStartsWith("PG");
assertEquals(6, results.size());
}
@Test
public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByDirectorEndsWith("Burton");
assertEquals(1, results.size());
}
@Test
public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByRatingNotContaining("PG");
assertEquals(1, results.size());
}
@Test
public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByDirectorNotLike("An%");
assertEquals(5, results.size());
}
}
@@ -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,64 @@
package com.baeldung.repository;
import com.baeldung.entity.Customer;
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.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import static org.junit.Assert.assertEquals;
@DataJpaTest
@RunWith(SpringRunner.class)
public class CustomerRepositoryIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private CustomerRepository repository;
@Before
public void before() {
entityManager.persist(new Customer("A", "A@example.com"));
entityManager.persist(new Customer("D", null));
entityManager.persist(new Customer("D", "D@example.com"));
}
@Test
public void givenQueryMethod_whenEmailIsNull_thenFoundByNullEmail() {
List<Customer> customers = repository.findByNameAndEmail("D", null);
assertEquals(1, customers.size());
Customer actual = customers.get(0);
assertEquals(null, actual.getEmail());
assertEquals("D", actual.getName());
}
@Test
public void givenQueryMethod_whenEmailIsAbsent_thenIgnoreEmail() {
List<Customer> customers = repository.findByName("D");
assertEquals(2, customers.size());
}
@Test
public void givenQueryAnnotation_whenEmailIsNull_thenIgnoreEmail() {
List<Customer> customers = repository.findCustomerByNameAndEmail("D", null);
assertEquals(2, customers.size());
}
@After
public void cleanUp() {
repository.deleteAll();
}
}
@@ -0,0 +1,39 @@
package com.baeldung.repository;
import static org.assertj.core.api.AssertionsForClassTypes.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.junit4.SpringRunner;
import com.baeldung.entity.Employee;
@RunWith(SpringRunner.class)
@DataJpaTest
public class EmployeeRepositoryIntegrationTest {
private static final Employee EMPLOYEE1 = new Employee(1L, "John");
private static final Employee EMPLOYEE2 = new Employee(2L, "Alice");
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void givenEmployeeEntity_whenInsertWithSave_ThenEmployeeIsPersisted() {
employeeRepository.save(EMPLOYEE1);
assertEmployeePersisted(EMPLOYEE1);
}
@Test
public void givenEmployeeEntity_whenInsertWithSaveAndFlush_ThenEmployeeIsPersisted() {
employeeRepository.saveAndFlush(EMPLOYEE2);
assertEmployeePersisted(EMPLOYEE2);
}
private void assertEmployeePersisted(Employee input) {
Employee employee = employeeRepository.getOne(input.getId());
assertThat(employee).isNotNull();
}
}
@@ -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,77 @@
package com.baeldung.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.jupiter.api.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.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import com.baeldung.entity.Fruit;
@RunWith(SpringRunner.class)
@SpringBootTest
class FruitRepositoryIntegrationTest {
@Autowired
private FruitRepository fruitRepository;
@Transactional
@Test
@Sql(scripts = { "/test-fruit-data.sql" })
public void givenFruits_WhenDeletedByColor_ThenDeletedFruitsShouldReturn() {
List<Fruit> fruits = fruitRepository.deleteByColor("green");
assertEquals("number of fruits are not matching", 2, fruits.size());
fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor()));
}
@Transactional
@Test
@Sql(scripts = { "/test-fruit-data.sql" })
public void givenFruits_WhenDeletedByName_ThenDeletedFruitCountShouldReturn() {
Long deletedFruitCount = fruitRepository.deleteByName("apple");
assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue());
}
@Transactional
@Test
@Sql(scripts = { "/test-fruit-data.sql" })
public void givenFruits_WhenRemovedByColor_ThenDeletedFruitsShouldReturn() {
List<Fruit> fruits = fruitRepository.removeByColor("green");
assertEquals("number of fruits are not matching", 2, fruits.size());
fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor()));
}
@Transactional
@Test
@Sql(scripts = { "/test-fruit-data.sql" })
public void givenFruits_WhenRemovedByName_ThenDeletedFruitCountShouldReturn() {
Long deletedFruitCount = fruitRepository.removeByName("apple");
assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue());
}
@Transactional
@Test
@Sql(scripts = { "/test-fruit-data.sql" })
public void givenFruits_WhenDeletedByColorOrName_ThenDeletedFruitsShouldReturn() {
List<Fruit> fruits = fruitRepository.deleteFruits("apple", "green");
assertEquals("number of fruits are not matching", 3, fruits.size());
fruits.forEach(fruit -> assertTrue("Its not a green fruit or apple", ("green".equals(fruit.getColor())) || "apple".equals(fruit.getColor())));
}
}
@@ -0,0 +1,54 @@
package com.baeldung.repository;
import com.baeldung.entity.Passenger;
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.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.IsNot.not;
@DataJpaTest
@RunWith(SpringRunner.class)
public class PassengerRepositoryIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private PassengerRepository repository;
@Before
public void before() {
entityManager.persist(Passenger.from("Jill", "Smith"));
entityManager.persist(Passenger.from("Eve", "Jackson"));
entityManager.persist(Passenger.from("Fred", "Bloggs"));
entityManager.persist(Passenger.from("Ricki", "Bobbie"));
entityManager.persist(Passenger.from("Siya", "Kolisi"));
}
@Test
public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() {
Passenger jill = Passenger.from("Jill", "Smith");
Passenger eve = Passenger.from("Eve", "Jackson");
Passenger fred = Passenger.from("Fred", "Bloggs");
Passenger siya = Passenger.from("Siya", "Kolisi");
Passenger ricki = Passenger.from("Ricki", "Bobbie");
List<Passenger> passengers = repository.findByFirstNameIgnoreCase("FRED");
assertThat(passengers, contains(fred));
assertThat(passengers, not(contains(eve)));
assertThat(passengers, not(contains(siya)));
assertThat(passengers, not(contains(jill)));
assertThat(passengers, not(contains(ricki)));
}
}
@@ -0,0 +1,57 @@
package com.baeldung.repository;
import com.baeldung.entity.Song;
import org.junit.jupiter.api.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.jdbc.Sql;
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
@Sql(scripts = { "/test-song-data.sql" })
public class SongRepositoryIntegrationTest {
@Autowired private SongRepository songRepository;
@Transactional
@Test
public void givenSong_WhenFindLikeByName_ThenShouldReturnOne() {
List<Song> songs = songRepository.findByNameLike("Despacito");
assertEquals(1, songs.size());
}
@Transactional
@Test
public void givenSong_WhenFindByNameNotLike_thenShouldReturn3Songs() {
List<Song> songs = songRepository.findByNameNotLike("Despacito");
assertEquals(5, songs.size());
}
@Transactional
@Test
public void givenSong_WhenFindByNameStartingWith_thenShouldReturn2Songs() {
List<Song> songs = songRepository.findByNameStartingWith("Co");
assertEquals(2, songs.size());
}
@Transactional
@Test
public void givenSong_WhenFindByNameEndingWith_thenShouldReturn2Songs() {
List<Song> songs = songRepository.findByNameEndingWith("Life");
assertEquals(2, songs.size());
}
@Transactional
@Test
public void givenSong_WhenFindBySingerContaining_thenShouldReturn2Songs() {
List<Song> songs = songRepository.findBySingerContaining("Luis");
assertEquals(2, songs.size());
}
}
@@ -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');
@@ -0,0 +1,4 @@
insert into fruit(id,name,color) values (1,'apple','red');
insert into fruit(id,name,color) values (2,'custard apple','green');
insert into fruit(id,name,color) values (3,'mango','yellow');
insert into fruit(id,name,color) values (4,'guava','green');
@@ -0,0 +1 @@
DELETE FROM Movie;
@@ -0,0 +1,7 @@
INSERT INTO movie(id, title, director, rating, duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132);
INSERT INTO movie(id, title, director, rating, duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181);
INSERT INTO movie(id, title, director, rating, duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123);
INSERT INTO movie(id, title, director, rating, duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112);
INSERT INTO movie(id, title, director, rating, duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102);
INSERT INTO movie(id, title, director, rating, duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128);
INSERT INTO movie(id, title, director, rating, duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100);
@@ -0,0 +1,8 @@
INSERT INTO song(id,name,length_in_seconds,compositor,singer,released,genre)
VALUES
(1,'Despacito',209,'Luis Fonsi','Luis Fonsi, Daddy Yankee','2017-01-12','Reggaeton'),
(2,'Con calma',188,'Daddy Yankee','Daddy Yankee','2019-01-24','Reggaeton'),
(3,'It''s My Life',205,'Bon Jovi','Jon Bon Jovi','2000-05-23','Pop'),
(4,'Live is Life',242,'Opus','Opus','1985-01-01','Reggae'),
(5,'Countdown to Extinction',249,'Megadeth','Megadeth','1992-07-14','Heavy Metal'),
(6, 'Si nos dejan',139,'Luis Miguel','Luis Miguel','1995-10-17','Bolero');