[BAEL-2538] Added tutorial queries and tests

This commit is contained in:
dupirefr 2019-02-05 18:41:57 +01:00
parent 8a9aba5d89
commit 04749e3313
6 changed files with 277 additions and 36 deletions

View File

@ -0,0 +1,25 @@
package com.baeldung.util;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Optional;
@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate localDate) {
return Optional.ofNullable(localDate)
.map(Date::valueOf)
.orElse(null);
}
@Override
public LocalDate convertToEntityAttribute(Date date) {
return Optional.ofNullable(date)
.map(Date::toLocalDate)
.orElse(null);
}
}

View File

@ -10,6 +10,7 @@ import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
@ -18,6 +19,9 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
Stream<User> findAllByName(String name);
@Query("select u from User u where u.email like '%@gmail.com'")
List<User> findUsersWithGmailAddress();
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@ -67,4 +71,19 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Modifying
@Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name);
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")
void deleteDeactivatedUsers();
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "alter table USERS.USERS add column deleted int(1) not null default 0", nativeQuery = true)
void addDeletedColumn();
}

View File

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

View File

@ -1,8 +1,11 @@
package com.baeldung.dao.repositories.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;
@ -40,4 +43,15 @@ public class UserRepositoryCustomImpl implements UserRepositoryCustom {
.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,7 +1,9 @@
package com.baeldung.domain.user;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "users", schema = "users")
@ -11,6 +13,9 @@ public class User {
@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;
@ -22,10 +27,12 @@ public class User {
super();
}
public User(String name, String email, Integer status) {
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() {
@ -44,6 +51,10 @@ public class User {
this.name = name;
}
public LocalDate getCreationDate() {
return creationDate;
}
public String getEmail() {
return email;
}
@ -83,4 +94,37 @@ public class User {
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,12 +1,12 @@
package com.baeldung.dao.repositories;
package com.baeldung.dao.repositories.user;
import com.baeldung.config.PersistenceConfiguration;
import com.baeldung.dao.repositories.user.UserRepository;
import com.baeldung.domain.user.User;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@ -17,13 +17,15 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
/**
* Created by adam.
@ -48,6 +50,8 @@ public class UserRepositoryIntegrationTest {
@Autowired
private UserRepository userRepository;
@Autowired
private EntityManager entityManager;
@Test
@Transactional
@ -270,9 +274,9 @@ public class UserRepositoryIntegrationTest {
@Test
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
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"));
@ -282,9 +286,9 @@ public class UserRepositoryIntegrationTest {
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
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"));
@ -296,9 +300,9 @@ public class UserRepositoryIntegrationTest {
@Test
public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
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(new Sort("name"));
@ -310,12 +314,12 @@ public class UserRepositoryIntegrationTest {
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
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(new PageRequest(1, 3));
@ -326,12 +330,12 @@ public class UserRepositoryIntegrationTest {
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
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(new PageRequest(1, 3));
@ -343,10 +347,10 @@ public class UserRepositoryIntegrationTest {
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
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");
@ -356,10 +360,10 @@ public class UserRepositoryIntegrationTest {
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
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");
@ -391,6 +395,137 @@ public class UserRepositoryIntegrationTest {
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@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.org", 1);
usr02.setLastLoginDate(LocalDate.of(2018, 7, 20));
usr02.setActive(false);
userRepository.save(usr01);
userRepository.save(usr02);
userRepository.deleteDeactivatedUsers();
List<User> users = userRepository.findAll();
assertEquals(1, users.size());
assertEquals(usr01, users.get(0));
}
@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.USERS where NAME = 'usr01'");
assertEquals(0, nativeQuery.getResultList().get(0));
}
@After
public void cleanUp() {
userRepository.deleteAll();