[BAEL-14321] - Moved @Query article code

This commit is contained in:
amit2103 2019-05-13 00:47:34 +05:30
parent 2ef9b4eb6f
commit 3e0d3242d2
10 changed files with 1017 additions and 2 deletions

View File

@ -6,7 +6,6 @@
- [Spring JPA Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
- [Spring Data JPA Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)

View File

@ -10,6 +10,7 @@
- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
### Eclipse Config

View File

@ -98,7 +98,16 @@
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
</dependency>
</dependencies>
<build>
@ -109,6 +118,25 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
@ -121,6 +149,7 @@
<spring-data-jpa.version>2.1.6.RELEASE</spring-data-jpa.version>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version>
<querydsl.version>4.2.1</querydsl.version>
<!-- util -->
<guava.version>21.0</guava.version>

View File

@ -0,0 +1,98 @@
package org.baeldung.spring.data.persistence.dao.user;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
import org.baeldung.spring.data.persistence.model.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;
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

@ -0,0 +1,14 @@
package org.baeldung.spring.data.persistence.dao.user;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import org.baeldung.spring.data.persistence.model.User;
public interface UserRepositoryCustom {
List<User> findUserByEmails(Set<String> emails);
List<User> findAllUsersByPredicates(Collection<Predicate<User>> predicates);
}

View File

@ -0,0 +1,57 @@
package org.baeldung.spring.data.persistence.dao.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 org.baeldung.spring.data.persistence.model.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

@ -0,0 +1,86 @@
package org.baeldung.spring.data.persistence.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@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

@ -0,0 +1,132 @@
package org.baeldung.spring.data.persistence.model;
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

@ -0,0 +1,561 @@
package org.baeldung.spring.data.persistence.dao.user;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.baeldung.spring.data.persistence.config.PersistenceConfig;
import org.baeldung.spring.data.persistence.model.User;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class UserRepositoryCommon {
final String USER_EMAIL = "email@example.com";
final String USER_EMAIL2 = "email2@example.com";
final String USER_EMAIL3 = "email3@example.com";
final String USER_EMAIL4 = "email4@example.com";
final Integer INACTIVE_STATUS = 0;
final Integer ACTIVE_STATUS = 1;
final String USER_EMAIL5 = "email5@example.com";
final String USER_EMAIL6 = "email6@example.com";
final String USER_NAME_ADAM = "Adam";
final String USER_NAME_PETER = "Peter";
@Autowired
protected UserRepository userRepository;
@Autowired
private EntityManager entityManager;
@Test
@Transactional
public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
User user4 = new User();
user4.setName("SAMPLE");
user4.setEmail(USER_EMAIL4);
userRepository.save(user4);
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count()).isEqualTo(3l);
}
}
@Test
public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAllUsers(Sort.by("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3));
assertThat(usersPage.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3));
assertThat(usersSortByNameLength.getContent()
.get(0)
.getName()).isEqualTo(USER_NAME_PETER);
}
@Test
@Transactional
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test
public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() {
User user1 = new User();
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
Set<String> emails = new HashSet<>();
emails.add(USER_EMAIL2);
emails.add(USER_EMAIL3);
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindByNameListReturnCollection() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
List<String> names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER);
List<User> usersWithNames = userRepository.findUserByNameList(names);
assertThat(usersWithNames.size()).isEqualTo(2);
}
@Test
@Transactional
public void whenInsertedWithQuery_ThenUserIsPersisted() {
userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true);
userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true);
User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM);
User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER);
assertThat(userAdam).isNotNull();
assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL);
assertThat(userPeter).isNotNull();
assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2);
}
@Test
@Transactional
public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() {
User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1);
User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1);
userRepository.save(usr01);
userRepository.save(usr02);
try (Stream<User> users = userRepository.findAllByName("usr01")) {
assertTrue(users.allMatch(usr -> usr.equals(usr01)));
}
}
@Test
@Transactional
public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() {
User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1);
User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1);
userRepository.save(usr01);
userRepository.save(usr02);
try (Stream<User> users = userRepository.findAllByName("usr00")) {
assertEquals(0, users.count());
}
}
@Test
public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() {
User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1);
User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1);
userRepository.save(usr01);
userRepository.save(usr02);
List<User> users = userRepository.findUsersWithGmailAddress();
assertEquals(1, users.size());
assertEquals(usr02, users.get(0));
}
@Test
@Transactional
public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() {
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1);
userRepository.save(usr01);
userRepository.save(usr02);
userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1));
List<User> users = userRepository.findAll();
assertEquals(1, users.size());
assertEquals(usr01, users.get(0));
}
@Test
public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() {
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1);
userRepository.save(usr01);
userRepository.save(usr02);
List<Predicate<User>> predicates = new ArrayList<>();
predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31)));
predicates.add(usr -> usr.getEmail().endsWith(".com"));
List<User> users = userRepository.findAllUsersByPredicates(predicates);
assertEquals(1, users.size());
assertEquals(usr01, users.get(0));
}
@Test
@Transactional
public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() {
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
usr01.setLastLoginDate(LocalDate.now());
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1);
usr02.setLastLoginDate(LocalDate.of(2018, 7, 20));
userRepository.save(usr01);
userRepository.save(usr02);
userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1));
List<User> users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name")));
assertTrue(users.get(0).isActive());
assertFalse(users.get(1).isActive());
}
@Test
@Transactional
public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() {
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
usr01.setLastLoginDate(LocalDate.now());
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0);
usr02.setLastLoginDate(LocalDate.of(2018, 7, 20));
usr02.setActive(false);
userRepository.save(usr01);
userRepository.save(usr02);
int deletedUsersCount = userRepository.deleteDeactivatedUsers();
List<User> users = userRepository.findAll();
assertEquals(1, users.size());
assertEquals(usr01, users.get(0));
assertEquals(1, deletedUsersCount);
}
@Test
@Transactional
public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() {
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
usr01.setLastLoginDate(LocalDate.now());
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1);
usr02.setLastLoginDate(LocalDate.of(2018, 7, 20));
usr02.setActive(false);
userRepository.save(usr01);
userRepository.save(usr02);
userRepository.addDeletedColumn();
Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'");
assertEquals(0, nativeQuery.getResultList().get(0));
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
}

View File

@ -0,0 +1,38 @@
package org.baeldung.spring.data.persistence.dao.user;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDate;
import org.baeldung.spring.data.persistence.config.PersistenceConfig;
import org.baeldung.spring.data.persistence.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by adam.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class UserRepositoryIntegrationTest extends UserRepositoryCommon {
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS));
userRepository.flush();
int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
}