JAVA-32815 Split or move spring-data-jpa-simple (#16322)

Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
timis1
2024-04-16 09:59:28 +03:00
committed by GitHub
parent b97a573c15
commit ebd95b4840
38 changed files with 73 additions and 78 deletions
@@ -0,0 +1,15 @@
package com.baeldung.simple;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories("com.baeldung.simple.repository")
public class JpaApplication {
public static void main(String[] args) {
SpringApplication.run(JpaApplication.class, args);
}
}
@@ -0,0 +1,75 @@
package com.baeldung.simple.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
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 org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@PropertySource("classpath:persistence.properties")
@EnableTransactionManagement
//@ImportResource("classpath*:*springDataConfig.xml")
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.simple.entity");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
}
@@ -0,0 +1,57 @@
package com.baeldung.simple.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private String isbn;
public Book() {
}
public Book(String title, String author, String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
}
@@ -0,0 +1,77 @@
package com.baeldung.simple.entity;
import java.io.Serializable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Foo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long 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 + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
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("Foo [name=").append(name).append("]");
return builder.toString();
}
}
@@ -0,0 +1,71 @@
package com.baeldung.simple.entity;
import java.time.ZonedDateTime;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Table(name = "users")
@Entity
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private ZonedDateTime birthDate;
private Boolean active;
public User() {
}
public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) {
this.name = name;
this.age = age;
this.birthDate = birthDate;
this.active = active;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public ZonedDateTime getBirthDate() {
return birthDate;
}
public void setBirthDate(ZonedDateTime birthDate) {
this.birthDate = birthDate;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.simple.repository;
import java.util.List;
import org.springframework.data.repository.ListCrudRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.simple.entity.Book;
@Repository
public interface BookListRepository extends ListCrudRepository<Book, Long> {
List<Book> findBooksByAuthor(String author);
}
@@ -0,0 +1,16 @@
package com.baeldung.simple.repository;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.ListCrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.simple.entity.Book;
@Repository
public interface BookPagingAndSortingRepository extends PagingAndSortingRepository<Book, Long>, ListCrudRepository<Book, Long> {
List<Book> findBooksByAuthor(String author, Pageable pageable);
}
@@ -0,0 +1,15 @@
package com.baeldung.simple.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.baeldung.simple.entity.Foo;
public interface IFooDAO extends JpaRepository<Foo, Long> {
Foo findByName(String name);
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);
}
@@ -0,0 +1,65 @@
package com.baeldung.simple.repository;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.simple.entity.User;
public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
List<User> findByName(String name);
List<User> findByNameIs(String name);
List<User> findByNameEquals(String name);
List<User> findByNameIsNull();
List<User> findByNameNot(String name);
List<User> findByNameIsNot(String name);
List<User> findByNameStartingWith(String name);
List<User> findByNameEndingWith(String name);
List<User> findByNameContaining(String name);
List<User> findByNameLike(String name);
List<User> findByAgeLessThan(Integer age);
List<User> findByAgeLessThanEqual(Integer age);
List<User> findByAgeGreaterThan(Integer age);
List<User> findByAgeGreaterThanEqual(Integer age);
List<User> findByAgeBetween(Integer startAge, Integer endAge);
List<User> findByBirthDateAfter(ZonedDateTime birthDate);
List<User> findByBirthDateBefore(ZonedDateTime birthDate);
List<User> findByActiveTrue();
List<User> findByActiveFalse();
List<User> findByAgeIn(Collection<Integer> ages);
List<User> findByNameOrAge(String name, Integer age);
List<User> findByNameOrAgeAndActive(String name, Integer age, Boolean active);
List<User> findByNameOrderByName(String name);
List<User> findByNameOrderByNameDesc(String name);
List<User> findByNameIsNotNull();
List<User> findByNameOrderByNameAsc(String name);
}
@@ -0,0 +1,16 @@
package com.baeldung.simple.repository;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import com.baeldung.simple.entity.User;
public interface UserRepositoryCustom {
List<User> findUserByEmails(Set<String> emails);
List<User> findAllUsersByPredicates(Collection<Predicate<User>> predicates);
}
@@ -0,0 +1,57 @@
package com.baeldung.simple.repository;
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 com.baeldung.simple.entity.User;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
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());
}
}
@@ -0,0 +1,19 @@
package com.baeldung.simple.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.simple.entity.Foo;
import com.baeldung.simple.repository.IFooDAO;
@Service
public class FooService implements IFooService {
@Autowired
private IFooDAO dao;
@Override
public Foo create(Foo foo) {
return dao.save(foo);
}
}
@@ -0,0 +1,7 @@
package com.baeldung.simple.service;
import com.baeldung.simple.entity.Foo;
public interface IFooService {
Foo create(Foo foo);
}
@@ -0,0 +1,30 @@
package com.baeldung.simple;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.baeldung.simple.entity.Book;
import com.baeldung.simple.repository.BookListRepository;
@SpringBootTest(classes = JpaApplication.class)
class BookListRepositoryIntegrationTest {
@Autowired
private BookListRepository bookListRepository;
@Test
void givenDbContainsBooks_whenFindBooksByAuthor_thenReturnBooksByAuthor() {
Book book1 = new Book("Spring Data", "John Doe", "1234567890");
Book book2 = new Book("Spring Data 2", "John Doe", "1234567891");
Book book3 = new Book("Spring Data 3", "John Doe", "1234567892");
bookListRepository.saveAll(Arrays.asList(book1, book2, book3));
List<Book> books = bookListRepository.findBooksByAuthor("John Doe");
Assertions.assertEquals(3, books.size());
}
}
@@ -0,0 +1,36 @@
package com.baeldung.simple;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import com.baeldung.simple.entity.Book;
import com.baeldung.simple.repository.BookPagingAndSortingRepository;
@SpringBootTest
class BookPagingAndSortingRepositoryIntegrationTest {
@Autowired
private BookPagingAndSortingRepository bookPagingAndSortingRepository;
@Test
void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() {
Book book1 = new Book("Spring Data", "John Miller", "1234567890");
Book book2 = new Book("Spring Data 2", "John Miller", "1234567891");
Book book3 = new Book("Spring Data 3", "John Miller", "1234567892");
bookPagingAndSortingRepository.saveAll(Arrays.asList(book1, book2, book3));
Pageable pageable = PageRequest.of(0, 2, Sort.by("title").descending());
List<Book> books = bookPagingAndSortingRepository.findBooksByAuthor("John Miller", pageable);
Assertions.assertEquals(2, books.size());
Assertions.assertEquals(book3.getId(), books.get(0).getId());
Assertions.assertEquals(book2.getId(), books.get(1).getId());
}
}
@@ -0,0 +1,31 @@
package com.baeldung.simple;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.simple.entity.Foo;
import com.baeldung.simple.service.IFooService;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { JpaApplication.class})
@DirtiesContext
public class FooServiceIntegrationTest {
@Autowired
private IFooService service;
@Autowired
private DataSource dataSource;
@Test(expected = DataIntegrityViolationException.class)
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo());
}
}
@@ -0,0 +1,191 @@
package com.baeldung.simple;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.simple.entity.User;
import com.baeldung.simple.repository.UserRepository;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = JpaApplication.class)
class UserRepositoryIntegrationTest {
private static final String USER_NAME_ADAM = "Adam";
private static final String USER_NAME_EVE = "Eve";
private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now();
@Autowired
private UserRepository userRepository;
@BeforeEach
public void setUp() {
User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true);
User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false);
User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true);
User user4 = new User(null, 30, BIRTHDATE, false);
userRepository.saveAll(Arrays.asList(user1, user2, user3, user4));
}
@AfterEach
public void tearDown() {
userRepository.deleteAll();
}
@Test
void whenFindByName_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByName(USER_NAME_ADAM)
.size());
}
@Test
void whenFindByNameIsNull_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameIsNull()
.size());
}
@Test
void whenFindByNameNot_thenReturnsCorrectResult() {
assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM)
.get(0)
.getName());
}
@Test
void whenFindByNameStartingWith_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByNameStartingWith("A")
.size());
}
@Test
void whenFindByNameEndingWith_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameEndingWith("e")
.size());
}
@Test
void whenByNameContaining_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameContaining("v")
.size());
}
@Test
void whenByNameLike_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByNameEndingWith("m")
.size());
}
@Test
void whenByAgeLessThan_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByAgeLessThan(25)
.size());
}
@Test
void whenByAgeLessThanEqual_thenReturnsCorrectResult() {
assertEquals(3, userRepository.findByAgeLessThanEqual(25)
.size());
}
@Test
void whenByAgeGreaterThan_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByAgeGreaterThan(25)
.size());
}
@Test
void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByAgeGreaterThanEqual(25)
.size());
}
@Test
void whenByAgeBetween_thenReturnsCorrectResult() {
assertEquals(4, userRepository.findByAgeBetween(20, 30)
.size());
}
@Test
void whenByBirthDateAfter_thenReturnsCorrectResult() {
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
assertEquals(4, userRepository.findByBirthDateAfter(yesterday)
.size());
}
@Test
void whenByBirthDateBefore_thenReturnsCorrectResult() {
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
assertEquals(0, userRepository.findByBirthDateBefore(yesterday)
.size());
}
@Test
void whenByActiveTrue_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByActiveTrue()
.size());
}
@Test
void whenByActiveFalse_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByActiveFalse()
.size());
}
@Test
void whenByAgeIn_thenReturnsCorrectResult() {
final List<Integer> ages = Arrays.asList(20, 25);
assertEquals(3, userRepository.findByAgeIn(ages)
.size());
}
@Test
void whenByNameOrAge() {
assertEquals(3, userRepository.findByNameOrAge(USER_NAME_ADAM, 20)
.size());
}
@Test
void whenByNameOrAgeAndActive() {
assertEquals(2, userRepository.findByNameOrAgeAndActive(USER_NAME_ADAM, 20, false)
.size());
}
@Test
void whenByNameOrderByName() {
assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM)
.size());
}
}