JAVA-66: removed old modules spring-data-jpa-*

This commit is contained in:
sampadawagde 2020-07-19 14:32:35 +05:30
parent 733d901d46
commit 3bebbd4c02
304 changed files with 0 additions and 13445 deletions

View File

@ -1,12 +0,0 @@
### 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)
- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions)

View File

@ -1,48 +0,0 @@
<?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>
<artifactId>spring-data-jpa-2</artifactId>
<name>spring-data-jpa-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<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>

View File

@ -1,13 +0,0 @@
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);
}
}

View File

@ -1,85 +0,0 @@
package com.baeldung.aggregation.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.util.Objects;
@Entity
public class Comment {
@Id
private Integer id;
private Integer year;
private boolean approved;
private String content;
@ManyToOne
private Post post;
public Comment() {
}
public Comment(int id, int year, boolean approved, String content, Post post) {
this.id = id;
this.year = year;
this.approved = approved;
this.content = content;
this.post = post;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Comment)) {
return false;
}
Comment comment = (Comment) o;
return getId().equals(comment.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
}

View File

@ -1,75 +0,0 @@
package com.baeldung.aggregation.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;
import java.util.Objects;
@Entity
public class Post {
@Id
private Integer id;
private String title;
private String content;
@OneToMany(mappedBy = "post")
private List<Comment> comments;
public Post() {
}
public Post(Integer id, String title, String content) {
this.id = id;
this.title = title;
this.content = content;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Post)) {
return false;
}
Post post = (Post) o;
return getId().equals(post.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.aggregation.model.custom;
public class CommentCount {
private Integer year;
private Long total;
public CommentCount(Integer year, Long total) {
this.year = year;
this.total = total;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
}

View File

@ -1,8 +0,0 @@
package com.baeldung.aggregation.model.custom;
public interface ICommentCount {
Integer getYearComment();
Long getTotalComment();
}

View File

@ -1,27 +0,0 @@
package com.baeldung.aggregation.repository;
import com.baeldung.aggregation.model.Comment;
import com.baeldung.aggregation.model.custom.CommentCount;
import com.baeldung.aggregation.model.custom.ICommentCount;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CommentRepository extends JpaRepository<Comment, Integer> {
@Query("SELECT c.year, COUNT(c.year) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC")
List<Object[]> countTotalCommentsByYear();
@Query("SELECT new com.baeldung.aggregation.model.custom.CommentCount(c.year, COUNT(c.year)) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC")
List<CommentCount> countTotalCommentsByYearClass();
@Query("SELECT c.year AS yearComment, COUNT(c.year) AS totalComment FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC")
List<ICommentCount> countTotalCommentsByYearInterface();
@Query(value = "SELECT c.year AS yearComment, COUNT(c.*) AS totalComment FROM comment AS c GROUP BY c.year ORDER BY c.year DESC", nativeQuery = true)
List<ICommentCount> countTotalCommentsByYearNative();
}

View File

@ -1,35 +0,0 @@
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;
}
}

View File

@ -1,51 +0,0 @@
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;
}
}

View File

@ -1,60 +0,0 @@
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;
}
}

View File

@ -1,19 +0,0 @@
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);
}

View File

@ -1,9 +0,0 @@
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> {
}

View File

@ -1,71 +0,0 @@
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;
}
}

View File

@ -1,38 +0,0 @@
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;
}
}

View File

@ -1,18 +0,0 @@
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);
}

View File

@ -1,37 +0,0 @@
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;
}
}

View File

@ -1,40 +0,0 @@
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;
}
}

View File

@ -1,78 +0,0 @@
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);
}
}

View File

@ -1,75 +0,0 @@
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;
}
}

View File

@ -1,43 +0,0 @@
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;
}
}

View File

@ -1,48 +0,0 @@
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;
}
}

View File

@ -1,13 +0,0 @@
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);
}

View File

@ -1,13 +0,0 @@
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);
}

View File

@ -1,48 +0,0 @@
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;
}
}

View File

@ -1,24 +0,0 @@
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);
}

View File

@ -1,45 +0,0 @@
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;
}
}

View File

@ -1,69 +0,0 @@
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;
}
}

View File

@ -1,44 +0,0 @@
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;
}
}

View File

@ -1,57 +0,0 @@
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;
}
}

View File

@ -1,47 +0,0 @@
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;
}
}

View File

@ -1,11 +0,0 @@
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);
}

View File

@ -1,14 +0,0 @@
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);
}

View File

@ -1,7 +0,0 @@
package com.baeldung.projection.view;
public interface AddressView {
String getZipCode();
PersonView getPerson();
}

View File

@ -1,34 +0,0 @@
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);
}
}

View File

@ -1,12 +0,0 @@
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();
}

View File

@ -1,19 +0,0 @@
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);
}

View File

@ -1,27 +0,0 @@
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")
int deleteFruits(@Param("name") String name, @Param("color") String color);
}

View File

@ -1,14 +0,0 @@
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);
}

View File

@ -1,21 +0,0 @@
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);
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<fruit>
<id>1</id>
<name>apple</name>
<color>red</color>
</fruit>

View File

@ -1 +0,0 @@
spring.datasource.data=classpath:db/import_joins.sql

View File

@ -1 +0,0 @@
spring.jpa.show-sql=true

View File

@ -1,13 +0,0 @@
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;

View File

@ -1,14 +0,0 @@
[
{
"_class": "com.baeldung.entity.Fruit",
"name": "apple",
"color": "red",
"id": 1
},
{
"_class": "com.baeldung.entity.Fruit",
"name": "guava",
"color": "green",
"id": 2
}
]

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<fruit>
<id>2</id>
<name>guava</name>
<color>green</color>
</fruit>

View File

@ -1,107 +0,0 @@
package com.baeldung.aggregation;
import com.baeldung.aggregation.model.custom.CommentCount;
import com.baeldung.aggregation.model.custom.ICommentCount;
import com.baeldung.aggregation.repository.CommentRepository;
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 java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@DataJpaTest
@Sql(scripts = "/test-aggregation-data.sql")
public class SpringDataAggregateIntegrationTest {
@Autowired
private CommentRepository commentRepository;
@Test
public void whenQueryWithAggregation_thenReturnResult() {
List<Object[]> commentCountsByYear = commentRepository.countTotalCommentsByYear();
Object[] countYear2019 = commentCountsByYear.get(0);
assertThat(countYear2019[0], is(Integer.valueOf(2019)));
assertThat(countYear2019[1], is(1l));
Object[] countYear2018 = commentCountsByYear.get(1);
assertThat(countYear2018[0], is(Integer.valueOf(2018)));
assertThat(countYear2018[1], is(2l));
Object[] countYear2017 = commentCountsByYear.get(2);
assertThat(countYear2017[0], is(Integer.valueOf(2017)));
assertThat(countYear2017[1], is(1l));
}
@Test
public void whenQueryWithAggregation_thenReturnCustomResult() {
List<CommentCount> commentCountsByYear = commentRepository.countTotalCommentsByYearClass();
CommentCount countYear2019 = commentCountsByYear.get(0);
assertThat(countYear2019.getYear(), is(Integer.valueOf(2019)));
assertThat(countYear2019.getTotal(), is(1l));
CommentCount countYear2018 = commentCountsByYear.get(1);
assertThat(countYear2018.getYear(), is(Integer.valueOf(2018)));
assertThat(countYear2018.getTotal(), is(2l));
CommentCount countYear2017 = commentCountsByYear.get(2);
assertThat(countYear2017.getYear(), is(Integer.valueOf(2017)));
assertThat(countYear2017.getTotal(), is(1l));
}
@Test
public void whenQueryWithAggregation_thenReturnInterfaceResult() {
List<ICommentCount> commentCountsByYear = commentRepository.countTotalCommentsByYearInterface();
ICommentCount countYear2019 = commentCountsByYear.get(0);
assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019)));
assertThat(countYear2019.getTotalComment(), is(1l));
ICommentCount countYear2018 = commentCountsByYear.get(1);
assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018)));
assertThat(countYear2018.getTotalComment(), is(2l));
ICommentCount countYear2017 = commentCountsByYear.get(2);
assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017)));
assertThat(countYear2017.getTotalComment(), is(1l));
}
@Test
public void whenNativeQueryWithAggregation_thenReturnInterfaceResult() {
List<ICommentCount> commentCountsByYear = commentRepository.countTotalCommentsByYearNative();
ICommentCount countYear2019 = commentCountsByYear.get(0);
assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019)));
assertThat(countYear2019.getTotalComment(), is(1l));
ICommentCount countYear2018 = commentCountsByYear.get(1);
assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018)));
assertThat(countYear2018.getTotalComment(), is(2l));
ICommentCount countYear2017 = commentCountsByYear.get(2);
assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017)));
assertThat(countYear2017.getTotalComment(), is(1l));
}
}

View File

@ -1,72 +0,0 @@
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);
}
}

View File

@ -1,60 +0,0 @@
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);
}
}

View File

@ -1,125 +0,0 @@
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());
}
}

View File

@ -1,39 +0,0 @@
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);
}
}

View File

@ -1,87 +0,0 @@
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();
}
}

View File

@ -1,142 +0,0 @@
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");
}
}

View File

@ -1,63 +0,0 @@
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");
}
}

View File

@ -1,64 +0,0 @@
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();
}
}

View File

@ -1,38 +0,0 @@
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 FruitPopulatorIntegrationTest {
@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());
}
});
}
}

View File

@ -1,75 +0,0 @@
package com.baeldung.repository;
import static org.junit.Assert.assertEquals;
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() {
int deletedCount = fruitRepository.deleteFruits("apple", "green");
assertEquals("number of fruits are not matching", 3, deletedCount);
}
}

View File

@ -1,54 +0,0 @@
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)));
}
}

View File

@ -1,58 +0,0 @@
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.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import com.baeldung.entity.Song;
@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());
}
}

View File

@ -1,7 +0,0 @@
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');

View File

@ -1,2 +0,0 @@
DELETE FROM address;
DELETE FROM person;

View File

@ -1,2 +0,0 @@
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');

View File

@ -1,7 +0,0 @@
INSERT INTO post (id, title, content) VALUES (1, 'Comment 1', 'Content 1');
INSERT INTO post (id, title, content) VALUES (2, 'Comment 2', 'Content 2');
INSERT INTO post (id, title, content) VALUES (3, 'Comment 3', 'Content 3');
INSERT INTO comment (id, year, approved, content, post_id) VALUES (1, 2019, false, 'Comment 1', 1);
INSERT INTO comment (id, year, approved, content, post_id) VALUES (2, 2018, true, 'Comment 2', 1);
INSERT INTO comment (id, year, approved, content, post_id) VALUES (3, 2018, true, 'Comment 3', 2);
INSERT INTO comment (id, year, approved, content, post_id) VALUES (4, 2017, false, 'Comment 4', 3);

View File

@ -1,6 +0,0 @@
truncate table fruit;
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');

View File

@ -1,8 +0,0 @@
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');

View File

@ -1,20 +0,0 @@
### Relevant Articles:
- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results)
- [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting)
- [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert)
- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)
- [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example)
- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test)
- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation)
- [Spring Data JPA Batch Inserts](https://www.baeldung.com/spring-data-jpa-batch-inserts)
- [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)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"
This can be ignored:
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
Or:
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator

View File

@ -1,71 +0,0 @@
<?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>
<artifactId>spring-data-jpa-3</artifactId>
<name>spring-data-jpa-3</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<!-- Prod Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</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>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Test containers only dependencies -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<!-- Test containers only dependencies -->
</dependencies>
<properties>
<datasource-proxy.version>1.4.1</datasource-proxy.version>
<guava.version>21.0</guava.version>
<testcontainers.version>1.12.2</testcontainers.version>
</properties>
</project>

View File

@ -1,14 +0,0 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -1,53 +0,0 @@
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();
}
}
}

View File

@ -1,45 +0,0 @@
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;
}
}

View File

@ -1,44 +0,0 @@
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;
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories("com.baeldung")
@EntityScan("com.baeldung")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -1,19 +0,0 @@
package com.baeldung.boot.daos;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.baeldung.boot.domain.Customer;
/**
* JPA CrudRepository interface
*
* @author ysharma2512
*
*/
@Repository
@Transactional
public interface CustomerRepository extends CrudRepository<Customer, Long>{
}

View File

@ -1,31 +0,0 @@
package com.baeldung.boot.daos.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.domain.Person;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
@Repository
public class PersonInsertRepository {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void insertWithQuery(Person person) {
entityManager.createNativeQuery("INSERT INTO person (id, first_name, last_name) VALUES (?,?,?)")
.setParameter(1, person.getId())
.setParameter(2, person.getFirstName())
.setParameter(3, person.getLastName())
.executeUpdate();
}
@Transactional
public void insertWithEntityManager(Person person) {
this.entityManager.persist(person);
}
}

View File

@ -1,99 +0,0 @@
package com.baeldung.boot.daos.user;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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 com.baeldung.boot.domain.User;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
public interface UserRepository extends JpaRepository<User, Integer> , UserRepositoryCustom{
Stream<User> findAllByName(String name);
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@Query("select u from User u where u.email like '%@gmail.com'")
List<User> findUsersWithGmailAddress();
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative();
@Query("SELECT u FROM User u WHERE u.status = ?1")
User findUserByStatus(Integer status);
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
User findUserByStatusNative(Integer status);
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
User findUserByStatusAndName(Integer status, String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
@Query("SELECT u FROM User u WHERE u.name like ?1%")
User findUserByNameLike(String name);
@Query("SELECT u FROM User u WHERE u.name like :name%")
User findUserByNameLikeNamedParam(@Param("name") String name);
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
User findUserByNameLikeNative(String name);
@Query(value = "SELECT u FROM User u")
List<User> findAllUsers(Sort sort);
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
@Modifying
@Query("update User u set u.status = :status where u.name = :name")
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@Modifying
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name);
@Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true)
@Modifying
void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active);
@Modifying
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNativePostgres(Integer status, String name);
@Query(value = "SELECT u FROM User u WHERE u.name IN :names")
List<User> findUserByNameList(@Param("names") Collection<String> names);
void deleteAllByCreationDateAfter(LocalDate date);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("update User u set u.active = false where u.lastLoginDate < :date")
void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete User u where u.active = false")
int deleteDeactivatedUsers();
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true)
void addDeletedColumn();
}

View File

@ -1,14 +0,0 @@
package com.baeldung.boot.daos.user;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import com.baeldung.boot.domain.User;
public interface UserRepositoryCustom {
List<User> findUserByEmails(Set<String> emails);
List<User> findAllUsersByPredicates(Collection<Predicate<User>> predicates);
}

View File

@ -1,57 +0,0 @@
package com.baeldung.boot.daos.user;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.baeldung.boot.domain.User;
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<User> findUserByEmails(Set<String> emails) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> user = query.from(User.class);
Path<String> emailPath = user.get("email");
List<Predicate> predicates = new ArrayList<>();
for (String email : emails) {
predicates.add(cb.like(emailPath, email));
}
query.select(user)
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query)
.getResultList();
}
@Override
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
Stream<User> allUsersStream = allUsers.stream();
for (java.util.function.Predicate<User> predicate : predicates) {
allUsersStream = allUsersStream.filter(predicate);
}
return allUsersStream.collect(Collectors.toList());
}
}

View File

@ -1,56 +0,0 @@
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Customer Entity class
* @author ysharma2512
*
*/
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = 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 String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
}

View File

@ -1,47 +0,0 @@
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Person {
@Id
private Long id;
private String firstName;
private String lastName;
public Person() {
}
public Person(Long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = 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;
}
}

View File

@ -1,83 +0,0 @@
package com.baeldung.boot.domain;
import javax.persistence.*;
import com.baeldung.boot.domain.Possession;
@Entity
@Table
public class Possession {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public Possession() {
super();
}
public Possession(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + (int) (id ^ (id >>> 32));
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Possession other = (Possession) obj;
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -1,132 +0,0 @@
package com.baeldung.boot.domain;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private LocalDate creationDate;
private LocalDate lastLoginDate;
private boolean active;
private int age;
@Column(unique = true, nullable = false)
private String email;
private Integer status;
@OneToMany
List<Possession> possessionList;
public User() {
super();
}
public User(String name, LocalDate creationDate,String email, Integer status) {
this.name = name;
this.creationDate = creationDate;
this.email = email;
this.status = status;
this.active = true;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public LocalDate getCreationDate() {
return creationDate;
}
public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(creationDate, user.creationDate) &&
Objects.equals(email, user.email) &&
Objects.equals(status, user.status);
}
@Override
public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status);
}
public LocalDate getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(LocalDate lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}

View File

@ -1,8 +0,0 @@
package com.baeldung.boot.passenger;
import java.util.List;
interface CustomPassengerRepository {
List<Passenger> findOrderedBySeatNumberLimitedTo(int limit);
}

View File

@ -1,82 +0,0 @@
package com.baeldung.boot.passenger;
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
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;
@Basic(optional = false)
@Column(nullable = false)
private Integer seatNumber;
private Passenger(String firstName, String lastName, Integer seatNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.seatNumber = seatNumber;
}
static Passenger from(String firstName, String lastName, Integer seatNumber) {
return new Passenger(firstName, lastName, seatNumber);
}
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
Passenger passenger = (Passenger) object;
return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFirstName(), passenger.getFirstName())
&& Objects.equals(getLastName(), passenger.getLastName());
}
@Override
public int hashCode() {
return Objects.hash(getFirstName(), getLastName(), getSeatNumber());
}
@Override
public String toString() {
final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName());
toStringBuilder.append("{ id=").append(id);
toStringBuilder.append(", firstName='").append(firstName).append('\'');
toStringBuilder.append(", lastName='").append(lastName).append('\'');
toStringBuilder.append(", seatNumber=").append(seatNumber);
toStringBuilder.append('}');
return toStringBuilder.toString();
}
Long getId() {
return id;
}
String getFirstName() {
return firstName;
}
String getLastName() {
return lastName;
}
Integer getSeatNumber() {
return seatNumber;
}
}

View File

@ -1,22 +0,0 @@
package com.baeldung.boot.passenger;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
interface PassengerRepository extends JpaRepository<Passenger, Long>, CustomPassengerRepository {
Passenger findFirstByOrderBySeatNumberAsc();
Passenger findTopByOrderBySeatNumberAsc();
List<Passenger> findByOrderBySeatNumberAsc();
List<Passenger> findByFirstNameIgnoreCase(String firstName);
List<Passenger> findByLastNameOrderBySeatNumberAsc(String lastName);
List<Passenger> findByLastName(String lastName, Sort sort);
}

View File

@ -1,20 +0,0 @@
package com.baeldung.boot.passenger;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Repository
class PassengerRepositoryImpl implements CustomPassengerRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<Passenger> findOrderedBySeatNumberLimitedTo(int limit) {
return entityManager.createQuery("SELECT p FROM Passenger p ORDER BY p.seatNumber",
Passenger.class).setMaxResults(limit).getResultList();
}
}

View File

@ -1,41 +0,0 @@
package com.baeldung.boot.web.controllers;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.boot.daos.CustomerRepository;
import com.baeldung.boot.domain.Customer;
/**
* A simple controller to test the JPA CrudRepository operations
* controllers
*
* @author ysharma2512
*
*/
@RestController
public class CustomerController {
CustomerRepository customerRepository;
public CustomerController(CustomerRepository customerRepository2) {
this.customerRepository = customerRepository2;
}
@PostMapping("/customers")
public ResponseEntity<List<Customer>> insertCustomers() throws URISyntaxException {
Customer c1 = new Customer("James", "Gosling");
Customer c2 = new Customer("Doug", "Lea");
Customer c3 = new Customer("Martin", "Fowler");
Customer c4 = new Customer("Brian", "Goetz");
List<Customer> customers = Arrays.asList(c1, c2, c3, c4);
customerRepository.saveAll(customers);
return ResponseEntity.ok(customers);
}
}

View File

@ -1,36 +0,0 @@
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;
}
}

View File

@ -1,42 +0,0 @@
package com.baeldung.model;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "users")
public class BasicUser {
@Id
@GeneratedValue
private Long id;
private String username;
@ElementCollection
private Set<String> permissions;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Set<String> getPermissions() {
return permissions;
}
public void setPermissions(Set<String> permissions) {
this.permissions = permissions;
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.multipledb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MultipleDbApplication {
public static void main(String[] args) {
SpringApplication.run(MultipleDbApplication.class, args);
}
}

View File

@ -1,68 +0,0 @@
package com.baeldung.multipledb;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
@PropertySource({"classpath:persistence-multiple-db.properties"})
@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
@Profile("!tc")
public class PersistenceProductConfiguration {
@Autowired
private Environment env;
public PersistenceProductConfiguration() {
super();
}
//
@Bean
public LocalContainerEntityManagerFactoryBean productEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(productDataSource());
em.setPackagesToScan("com.baeldung.multipledb.model.product");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
final HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
public DataSource productDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager productTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(productEntityManager().getObject());
return transactionManager;
}
}

View File

@ -1,13 +0,0 @@
package com.baeldung.multipledb.dao.product;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.baeldung.multipledb.model.product.Product;
public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {
List<Product> findAllByPrice(double price, Pageable pageable);
}

View File

@ -1,67 +0,0 @@
package com.baeldung.multipledb.model.product;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(schema = "products")
public class Product {
@Id
private int id;
private String name;
private double price;
public Product() {
super();
}
private Product(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public static Product from(int id, String name, double price) {
return new Product(id, name, price);
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(final double price) {
this.price = price;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Product [name=")
.append(name)
.append(", id=")
.append(id)
.append("]");
return builder.toString();
}
}

View File

@ -1,9 +0,0 @@
package com.baeldung.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

View File

@ -1,14 +0,0 @@
package com.baeldung.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.model.BasicUser;
public interface UserRepository extends JpaRepository<BasicUser, Long> {
Optional<BasicUser> findSummaryByUsername(String username);
Optional<BasicUser> findByUsername(String username);
}

View File

@ -1,6 +0,0 @@
spring.main.allow-bean-definition-overriding=true
spring.jpa.properties.hibernate.jdbc.batch_size=4
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.generate_statistics=true

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,13 +0,0 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS
product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS
jdbc.user=sa
jdbc.pass=sa
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false

View File

@ -1,17 +0,0 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,19 +0,0 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = Application.class)
public class SpringJpaContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,40 +0,0 @@
package com.baeldung.batchinserts;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.baeldung.boot.Application;
import com.baeldung.boot.daos.CustomerRepository;
import com.baeldung.boot.web.controllers.CustomerController;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
@AutoConfigureMockMvc
public class BatchInsertIntegrationTest {
@Autowired
private CustomerRepository customerRepository;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup( new CustomerController(customerRepository))
.build();
}
@Test
public void whenInsertingCustomers_thenCustomersAreCreated() throws Exception {
this.mockMvc.perform(post("/customers"))
.andExpect(status().isOk());
}
}

Some files were not shown because too many files have changed in this diff Show More