* BAEL-1412 add java 8 spring data features

* BAEL-21 new HTTP API overview

* BAEL-21 fix executor

* BAEL-1432 add custom gradle task

* BAEL-1567 add samples of cookie and session in serlvet

* BAEL-1567 use stream api

* BAEL-1567 fix optional

* BAEL-1679 add query annotation jpa spring data

* BAEL-1679 added new junits

* BAEL-1679 use assertJ, use givenWhenThen naming convention
This commit is contained in:
abialas 2018-04-24 03:58:19 +02:00 committed by KevinGilmore
parent b7a7a80968
commit 274745e3bb
3 changed files with 353 additions and 15 deletions

View File

@ -15,6 +15,14 @@ public class User {
private String name; private String name;
private Integer status; private Integer status;
public User() {
}
public User(String name, Integer status) {
this.name = name;
this.status = status;
}
public Integer getId() { public Integer getId() {
return id; return id;
} }

View File

@ -1,10 +1,20 @@
package org.baeldung.repository; package org.baeldung.repository;
import org.baeldung.model.User; import org.baeldung.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.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.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -21,4 +31,54 @@ public interface UserRepository extends JpaRepository<User, Integer> {
@Async @Async
CompletableFuture<User> findOneByStatus(Integer status); CompletableFuture<User> findOneByStatus(Integer status);
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@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 \n-- #pageable\n", 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);
} }

View File

@ -1,58 +1,65 @@
package org.baeldung.repository; package org.baeldung.repository;
import org.baeldung.boot.Application; import org.baeldung.boot.config.H2JpaConfig;
import org.baeldung.model.User; import org.baeldung.model.User;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
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.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Created by adam. * Created by adam.
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class) @SpringBootTest(classes = H2JpaConfig.class)
public class UserRepositoryIntegrationTest { public class UserRepositoryIntegrationTest {
private final String USER_NAME_ADAM = "Adam"; private final String USER_NAME_ADAM = "Adam";
private final String USER_NAME_PETER = "Peter";
private final Integer INACTIVE_STATUS = 0;
private final Integer ACTIVE_STATUS = 1; private final Integer ACTIVE_STATUS = 1;
@Autowired @Autowired private UserRepository userRepository;
private UserRepository userRepository;
@Test @Test
public void shouldReturnEmptyOptionalWhenSearchByNameInEmptyDB() { public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() {
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM); Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent(), equalTo(false)); assertThat(foundUser.isPresent()).isEqualTo(false);
} }
@Test @Test
public void shouldReturnOptionalWithPresentUserWhenExistsWithGivenName() { public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() {
User user = new User(); User user = new User();
user.setName(USER_NAME_ADAM); user.setName(USER_NAME_ADAM);
userRepository.save(user); userRepository.save(user);
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM); Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent(), equalTo(true)); assertThat(foundUser.isPresent()).isEqualTo(true);
assertThat(foundUser.get().getName(), equalTo(USER_NAME_ADAM)); assertThat(foundUser.get().getName()).isEqualTo(USER_NAME_ADAM);
} }
@Test @Test
@Transactional @Transactional
public void shouldReturnStreamOfUsersWithNameWhenExistWithSameGivenName() { public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() {
User user1 = new User(); User user1 = new User();
user1.setName(USER_NAME_ADAM); user1.setName(USER_NAME_ADAM);
userRepository.save(user1); userRepository.save(user1);
@ -70,12 +77,12 @@ public class UserRepositoryIntegrationTest {
userRepository.save(user4); userRepository.save(user4);
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count(), equalTo(3l)); assertThat(foundUsersStream.count()).isEqualTo(3l);
} }
} }
@Test @Test
public void shouldReturnUserWithGivenStatusAsync() throws ExecutionException, InterruptedException { public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException {
User user = new User(); User user = new User();
user.setName(USER_NAME_ADAM); user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS); user.setStatus(ACTIVE_STATUS);
@ -83,8 +90,271 @@ public class UserRepositoryIntegrationTest {
CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS);
assertThat(userByStatus.get().getName(), equalTo(USER_NAME_ADAM)); assertThat(userByStatus.get().getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
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 givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
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 givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
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 givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
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 givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", 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 givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage.getContent().get(0).getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength.getContent().get(0).getName()).isEqualTo("SAMPLE1");
}
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", ACTIVE_STATUS));
userRepository.flush();
int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
} }
@After @After