JAVA-66: New module spring-data-jpa-enterprise
This commit is contained in:
parent
2ca8ec847c
commit
2f81507076
24
persistence-modules/spring-data-jpa-enterprise/README.md
Normal file
24
persistence-modules/spring-data-jpa-enterprise/README.md
Normal file
@ -0,0 +1,24 @@
|
||||
## Spring Data JPA - Enterprise
|
||||
|
||||
This module contains articles about Spring Data JPA used in enterprise applications such as transactions, sessions, naming conventions and more
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Spring JPA – Multiple Databases](https://www.baeldung.com/spring-data-jpa-multiple-databases)
|
||||
- [Spring Data Java 8 Support](https://www.baeldung.com/spring-data-java-8)
|
||||
- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)
|
||||
- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test)
|
||||
- [A Guide to Spring’s Open Session In View](https://www.baeldung.com/spring-open-session-in-view)
|
||||
- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections)
|
||||
- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming)
|
||||
- [Partial Data Update with Spring Data](https://www.baeldung.com/spring-data-partial-update)
|
||||
|
||||
### 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
|
||||
|
107
persistence-modules/spring-data-jpa-enterprise/pom.xml
Normal file
107
persistence-modules/spring-data-jpa-enterprise/pom.xml
Normal file
@ -0,0 +1,107 @@
|
||||
<?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-enterprise</artifactId>
|
||||
<name>spring-data-jpa-enterprise</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-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-data-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-cache</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-envers</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-jdk8</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</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>
|
||||
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>1.3.1.Final</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring-boot-version>2.1.9.RELEASE</spring-boot-version>
|
||||
<start-class>com.baeldung.springdatageode.app.ClientCacheApp</start-class>
|
||||
<spring-geode-starter-version>1.1.1.RELEASE</spring-geode-starter-version>
|
||||
<spring.boot.starter.version>2.1.9.RELEASE</spring.boot.starter.version>
|
||||
<mapstruct.version>1.3.1.Final</mapstruct.version>
|
||||
<guava.version>21.0</guava.version>
|
||||
<testcontainers.version>1.12.2</testcontainers.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,13 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.boot.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import com.baeldung.boot.services.IBarService;
|
||||
import com.baeldung.boot.services.impl.BarSpringDataJpaService;
|
||||
|
||||
@Configuration
|
||||
@Profile("!tc")
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaAuditing
|
||||
public class PersistenceConfiguration {
|
||||
|
||||
@Bean
|
||||
public IBarService barSpringDataJpaService() {
|
||||
return new BarSpringDataJpaService();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.boot.daos;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public interface IBarCrudRepository extends CrudRepository<Bar, Serializable> {
|
||||
//
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.boot.daos;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
|
||||
public interface IFooDao extends JpaRepository<Foo, Long> {
|
||||
|
||||
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
|
||||
Foo retrieveByName(@Param("name") String name);
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
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();
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
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);
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,220 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import org.hibernate.annotations.OrderBy;
|
||||
import org.hibernate.envers.Audited;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.springframework.data.annotation.CreatedBy;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedBy;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
|
||||
@Audited
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class Bar implements Serializable {
|
||||
|
||||
private static Logger logger = Logger.getLogger(Bar.class);
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "id")
|
||||
private int id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
@OrderBy(clause = "NAME DESC")
|
||||
// @NotAudited
|
||||
private Set<Foo> fooSet = Sets.newHashSet();
|
||||
@Column(name = "operation")
|
||||
private String operation;
|
||||
@Column(name = "timestamp")
|
||||
private long timestamp;
|
||||
@Column(name = "created_date", updatable = false, nullable = false)
|
||||
@CreatedDate
|
||||
private long createdDate;
|
||||
@Column(name = "modified_date")
|
||||
@LastModifiedDate
|
||||
private long modifiedDate;
|
||||
@Column(name = "created_by")
|
||||
@CreatedBy
|
||||
private String createdBy;
|
||||
@Column(name = "modified_by")
|
||||
@LastModifiedBy
|
||||
private String modifiedBy;
|
||||
|
||||
public Bar() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Bar(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Foo> getFooSet() {
|
||||
return fooSet;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public void setFooSet(final Set<Foo> fooSet) {
|
||||
this.fooSet = fooSet;
|
||||
}
|
||||
|
||||
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 OPERATION getOperation() {
|
||||
return OPERATION.parse(operation);
|
||||
}
|
||||
|
||||
public void setOperation(final String operation) {
|
||||
this.operation = operation;
|
||||
}
|
||||
|
||||
public void setOperation(final OPERATION operation) {
|
||||
this.operation = operation.getValue();
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(final long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public long getCreatedDate() {
|
||||
return createdDate;
|
||||
}
|
||||
|
||||
public void setCreatedDate(final long createdDate) {
|
||||
this.createdDate = createdDate;
|
||||
}
|
||||
|
||||
public long getModifiedDate() {
|
||||
return modifiedDate;
|
||||
}
|
||||
|
||||
public void setModifiedDate(final long modifiedDate) {
|
||||
this.modifiedDate = modifiedDate;
|
||||
}
|
||||
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
public void setCreatedBy(final String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
public String getModifiedBy() {
|
||||
return modifiedBy;
|
||||
}
|
||||
|
||||
public void setModifiedBy(final String modifiedBy) {
|
||||
this.modifiedBy = modifiedBy;
|
||||
}
|
||||
|
||||
@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 Bar other = (Bar) 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("Bar [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@PrePersist
|
||||
public void onPrePersist() {
|
||||
logger.info("@PrePersist");
|
||||
audit(OPERATION.INSERT);
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void onPreUpdate() {
|
||||
logger.info("@PreUpdate");
|
||||
audit(OPERATION.UPDATE);
|
||||
}
|
||||
|
||||
@PreRemove
|
||||
public void onPreRemove() {
|
||||
logger.info("@PreRemove");
|
||||
audit(OPERATION.DELETE);
|
||||
}
|
||||
|
||||
private void audit(final OPERATION operation) {
|
||||
setOperation(operation);
|
||||
setTimestamp((new Date()).getTime());
|
||||
}
|
||||
|
||||
public enum OPERATION {
|
||||
INSERT, UPDATE, DELETE;
|
||||
private String value;
|
||||
|
||||
OPERATION() {
|
||||
value = toString();
|
||||
}
|
||||
|
||||
public static OPERATION parse(final String value) {
|
||||
OPERATION operation = null;
|
||||
for (final OPERATION op : OPERATION.values()) {
|
||||
if (op.getValue().equals(value)) {
|
||||
operation = op;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return operation;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import org.hibernate.envers.Audited;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)})
|
||||
@Entity
|
||||
@Audited
|
||||
// @Proxy(lazy = false)
|
||||
public class Foo implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
|
||||
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "BAR_ID")
|
||||
private Bar bar = new Bar();
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public Bar getBar() {
|
||||
return bar;
|
||||
}
|
||||
|
||||
public void setBar(final Bar bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
|
||||
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,83 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,132 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.boot.services;
|
||||
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
|
||||
public interface IBarService extends IOperations<Bar> {
|
||||
//
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.boot.services;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
|
||||
public interface IFooService extends IOperations<Foo> {
|
||||
|
||||
Foo retrieveByName(String name);
|
||||
|
||||
Page<Foo> findPaginated(Pageable pageable);
|
||||
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.boot.services;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
public interface IOperations<T extends Serializable> {
|
||||
|
||||
T findOne(final long id);
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
Page<T> findPaginated(int page, int size);
|
||||
|
||||
// write
|
||||
|
||||
T create(final T entity);
|
||||
|
||||
T update(final T entity);
|
||||
|
||||
void delete(final T entity);
|
||||
|
||||
void deleteById(final long entityId);
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.boot.services.impl;
|
||||
|
||||
import com.baeldung.boot.services.IOperations;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Transactional
|
||||
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
// read - one
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public T findOne(final long id) {
|
||||
return getDao().findById(id).orElse(null);
|
||||
}
|
||||
|
||||
// read - all
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<T> findPaginated(final int page, final int size) {
|
||||
return getDao().findAll(PageRequest.of(page, size));
|
||||
}
|
||||
|
||||
// write
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(final T entity) {
|
||||
getDao().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(final long entityId) {
|
||||
getDao().deleteById(entityId);
|
||||
}
|
||||
|
||||
protected abstract PagingAndSortingRepository<T, Long> getDao();
|
||||
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.baeldung.boot.services.impl;
|
||||
|
||||
import com.baeldung.boot.services.IOperations;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Transactional(value = "transactionManager")
|
||||
public abstract class AbstractSpringDataJpaService<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
@Override
|
||||
public T findOne(final long id) {
|
||||
return getDao().findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(final T entity) {
|
||||
getDao().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(final long entityId) {
|
||||
getDao().deleteById(entityId);
|
||||
}
|
||||
|
||||
protected abstract CrudRepository<T, Serializable> getDao();
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.boot.services.impl;
|
||||
|
||||
import com.baeldung.boot.daos.IBarCrudRepository;
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
import com.baeldung.boot.services.IBarService;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class BarSpringDataJpaService extends AbstractSpringDataJpaService<Bar> implements IBarService {
|
||||
|
||||
@Autowired
|
||||
private IBarCrudRepository dao;
|
||||
|
||||
public BarSpringDataJpaService() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CrudRepository<Bar, Serializable> getDao() {
|
||||
return dao;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<Bar> findPaginated(int page, int size) {
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.baeldung.boot.services.impl;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.baeldung.boot.daos.IFooDao;
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
import com.baeldung.boot.services.IFooService;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class FooService extends AbstractService<Foo> implements IFooService {
|
||||
|
||||
@Autowired
|
||||
private IFooDao dao;
|
||||
|
||||
public FooService() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
protected PagingAndSortingRepository<Foo, Long> getDao() {
|
||||
return dao;
|
||||
}
|
||||
|
||||
// custom methods
|
||||
|
||||
@Override
|
||||
public Foo retrieveByName(final String name) {
|
||||
return dao.retrieveByName(name);
|
||||
}
|
||||
|
||||
// overridden to be secured
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<Foo> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<Foo> findPaginated(Pageable pageable) {
|
||||
return dao.findAll(pageable);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.elementcollection;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ElementCollectionApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ElementCollectionApplication.class, args);
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.baeldung.elementcollection.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Employee {
|
||||
@Id
|
||||
private int id;
|
||||
private String name;
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "employee_phone", joinColumns = @JoinColumn(name = "employee_id"))
|
||||
private List<Phone> phones;
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Employee(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Phone> getPhones() {
|
||||
return phones;
|
||||
}
|
||||
|
||||
public void setPhones(List<Phone> phones) {
|
||||
this.phones = phones;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof Employee)) {
|
||||
return false;
|
||||
}
|
||||
Employee user = (Employee) o;
|
||||
return getId() == user.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getId());
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.baeldung.elementcollection.model;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Embeddable
|
||||
public class Phone {
|
||||
private String type;
|
||||
private String areaCode;
|
||||
private String number;
|
||||
|
||||
public Phone() {
|
||||
}
|
||||
|
||||
public Phone(String type, String areaCode, String number) {
|
||||
this.type = type;
|
||||
this.areaCode = areaCode;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getAreaCode() {
|
||||
return areaCode;
|
||||
}
|
||||
|
||||
public void setAreaCode(String areaCode) {
|
||||
this.areaCode = areaCode;
|
||||
}
|
||||
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public void setNumber(String number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof Phone)) {
|
||||
return false;
|
||||
}
|
||||
Phone phone = (Phone) o;
|
||||
return getType().equals(phone.getType()) && getAreaCode().equals(phone.getAreaCode())
|
||||
&& getNumber().equals(phone.getNumber());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getType(), getAreaCode(), getNumber());
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.elementcollection.repository;
|
||||
|
||||
import com.baeldung.elementcollection.model.Employee;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.persistence.EntityGraph;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Repository
|
||||
public class EmployeeRepository {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
@Transactional
|
||||
public void save(Employee employee) {
|
||||
em.persist(employee);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void remove(int id) {
|
||||
Employee employee = findById(id);
|
||||
em.remove(employee);
|
||||
}
|
||||
|
||||
public Employee findById(int id) {
|
||||
return em.find(Employee.class, id);
|
||||
}
|
||||
|
||||
public Employee findByJPQL(int id) {
|
||||
return em.createQuery("SELECT u FROM Employee AS u JOIN FETCH u.phones WHERE u.id=:id", Employee.class)
|
||||
.setParameter("id", id).getSingleResult();
|
||||
}
|
||||
|
||||
public Employee findByEntityGraph(int id) {
|
||||
EntityGraph<Employee> entityGraph = em.createEntityGraph(Employee.class);
|
||||
entityGraph.addAttributeNodes("name", "phones");
|
||||
Map<String, Object> properties = new HashMap<>();
|
||||
properties.put("javax.persistence.fetchgraph", entityGraph);
|
||||
return em.find(Employee.class, id, properties);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,71 @@
|
||||
package com.baeldung.multipledb;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
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.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
/**
|
||||
* By default, the persistence-multiple-db.properties file is read for
|
||||
* non auto configuration in PersistenceProductConfiguration.
|
||||
* <p>
|
||||
* If we need to use persistence-multiple-db-boot.properties and auto configuration
|
||||
* then uncomment the below @Configuration class and comment out PersistenceProductConfiguration.
|
||||
*/
|
||||
//@Configuration
|
||||
@PropertySource({"classpath:persistence-multiple-db-boot.properties"})
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
|
||||
@Profile("!tc")
|
||||
public class PersistenceProductAutoConfiguration {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceProductAutoConfiguration() {
|
||||
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
|
||||
@ConfigurationProperties(prefix="spring.second-datasource")
|
||||
public DataSource productDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager productTransactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(productEntityManager().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package com.baeldung.multipledb;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
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.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
/**
|
||||
* By default, the persistence-multiple-db.properties file is read for
|
||||
* non auto configuration in PersistenceUserConfiguration.
|
||||
* <p>
|
||||
* If we need to use persistence-multiple-db-boot.properties and auto configuration
|
||||
* then uncomment the below @Configuration class and comment out PersistenceUserConfiguration.
|
||||
*/
|
||||
//@Configuration
|
||||
@PropertySource({"classpath:persistence-multiple-db-boot.properties"})
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
|
||||
@Profile("!tc")
|
||||
public class PersistenceUserAutoConfiguration {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceUserAutoConfiguration() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean userEntityManager() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(userDataSource());
|
||||
em.setPackagesToScan("com.baeldung.multipledb.model.user");
|
||||
|
||||
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
|
||||
@Primary
|
||||
@ConfigurationProperties(prefix="spring.datasource")
|
||||
public DataSource userDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public PlatformTransactionManager userTransactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(userEntityManager().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
package com.baeldung.multipledb;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.*;
|
||||
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.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
|
||||
@Profile("!tc")
|
||||
public class PersistenceUserConfiguration {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceUserConfiguration() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean userEntityManager() {
|
||||
System.out.println("loading config");
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(userDataSource());
|
||||
em.setPackagesToScan("com.baeldung.multipledb.model.user");
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public DataSource userDataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("user.jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public PlatformTransactionManager userTransactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(userEntityManager().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
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);
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.multipledb.dao.user;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.baeldung.multipledb.model.user.PossessionMultipleDB;
|
||||
|
||||
public interface PossessionRepository extends JpaRepository<PossessionMultipleDB, Long> {
|
||||
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.multipledb.dao.user;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.baeldung.multipledb.model.user.UserMultipleDB;
|
||||
|
||||
public interface UserRepository extends JpaRepository<UserMultipleDB, Integer> {
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
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();
|
||||
}
|
||||
}
|
@ -0,0 +1,82 @@
|
||||
package com.baeldung.multipledb.model.user;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table
|
||||
public class PossessionMultipleDB {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
public PossessionMultipleDB() {
|
||||
super();
|
||||
}
|
||||
|
||||
public PossessionMultipleDB(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 PossessionMultipleDB other = (PossessionMultipleDB) 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();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,88 @@
|
||||
package com.baeldung.multipledb.model.user;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserMultipleDB {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private int id;
|
||||
private String name;
|
||||
private int age;
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
private Integer status;
|
||||
|
||||
@OneToMany
|
||||
List<PossessionMultipleDB> possessionList;
|
||||
|
||||
public UserMultipleDB() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserMultipleDB(String name, String email, Integer status) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
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 List<PossessionMultipleDB> getPossessionList() {
|
||||
return possessionList;
|
||||
}
|
||||
|
||||
public void setPossessionList(List<PossessionMultipleDB> 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();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import javax.persistence.Column;
|
||||
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 id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String firstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String lastName() {
|
||||
return lastName;
|
||||
}
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface PersonRepository extends JpaRepository<Person, Long> {
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.boot.model.naming.Identifier;
|
||||
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
|
||||
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
|
||||
|
||||
public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy {
|
||||
@Override
|
||||
protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) {
|
||||
return new Identifier(name.toLowerCase(), true);
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.boot.model.naming.Identifier;
|
||||
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
|
||||
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
|
||||
|
||||
public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy {
|
||||
@Override
|
||||
protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) {
|
||||
return new Identifier(name.toUpperCase(), true);
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringDataJpaNamingConventionApplication {
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.boot.model.naming.Identifier;
|
||||
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
|
||||
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
|
||||
|
||||
public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy {
|
||||
@Override
|
||||
protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) {
|
||||
return new Identifier(name.toLowerCase(), false);
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.boot.model.naming.Identifier;
|
||||
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
|
||||
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
|
||||
|
||||
public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy {
|
||||
@Override
|
||||
protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) {
|
||||
return new Identifier(name.toUpperCase(), false);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.osiv;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class OsivApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OsivApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.osiv.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;
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.osiv.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.osiv.model.BasicUser;
|
||||
|
||||
@Repository
|
||||
@Transactional
|
||||
public interface BasicUserRepository extends JpaRepository<BasicUser, Long> {
|
||||
|
||||
@EntityGraph(attributePaths = "permissions")
|
||||
Optional<BasicUser> findDetailedByUsername(String username);
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.osiv.service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.osiv.model.BasicUser;
|
||||
import com.baeldung.osiv.repository.BasicUserRepository;
|
||||
|
||||
@Service
|
||||
public class SimpleUserService implements UserService {
|
||||
|
||||
private final BasicUserRepository userRepository;
|
||||
|
||||
public SimpleUserService(BasicUserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<BasicUser> findOne(String username) {
|
||||
return userRepository.findDetailedByUsername(username);
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.osiv.service;
|
||||
|
||||
import com.baeldung.osiv.model.BasicUser;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserService {
|
||||
Optional<BasicUser> findOne(String username);
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.baeldung.osiv.web;
|
||||
|
||||
import com.baeldung.osiv.model.BasicUser;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class DetailedUserDto {
|
||||
|
||||
private Long id;
|
||||
private String username;
|
||||
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;
|
||||
}
|
||||
|
||||
public static DetailedUserDto fromEntity(BasicUser user) {
|
||||
DetailedUserDto detailed = new DetailedUserDto();
|
||||
detailed.setId(user.getId());
|
||||
detailed.setUsername(user.getUsername());
|
||||
detailed.setPermissions(user.getPermissions());
|
||||
|
||||
return detailed;
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.osiv.web;
|
||||
|
||||
import com.baeldung.osiv.service.UserService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/users")
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping("/{username}")
|
||||
public ResponseEntity<?> findOne(@PathVariable String username) {
|
||||
return userService.findOne(username)
|
||||
.map(DetailedUserDto::fromEntity)
|
||||
.map(ResponseEntity::ok)
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.partialupdate;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class PartialUpdateApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(PartialUpdateApplication.class, args);
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.partialupdate.model;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class ContactPhone {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
public long id;
|
||||
@Column(nullable=false)
|
||||
public long customerId;
|
||||
public String phone;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return phone;
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.partialupdate.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Customer {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
public long id;
|
||||
public String name;
|
||||
public String phone;
|
||||
//...
|
||||
public String phone99;
|
||||
|
||||
@Override public String toString() {
|
||||
return String.format("Customer %s, Phone: %s",
|
||||
this.name, this.phone);
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.partialupdate.model;
|
||||
|
||||
public class CustomerDto {
|
||||
private long id;
|
||||
public String name;
|
||||
public String phone;
|
||||
//...
|
||||
private String phone99;
|
||||
|
||||
public CustomerDto(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public CustomerDto(Customer c) {
|
||||
this.id = c.id;
|
||||
this.name = c.name;
|
||||
this.phone = c.phone;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public Customer convertToEntity() {
|
||||
Customer c = new Customer();
|
||||
c.id = id;
|
||||
c.name = name;
|
||||
c.phone = phone;
|
||||
return c;
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.partialupdate.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class CustomerStructured {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
public long id;
|
||||
public String name;
|
||||
@OneToMany(fetch = FetchType.EAGER, targetEntity = ContactPhone.class, mappedBy = "customerId")
|
||||
public List<ContactPhone> contactPhones;
|
||||
|
||||
@Override public String toString() {
|
||||
return String.format("Customer %s, Phone: %s",
|
||||
this.name, this.contactPhones.stream()
|
||||
.map(e -> e.toString()).reduce("", String::concat));
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.partialupdate.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.partialupdate.model.ContactPhone;
|
||||
|
||||
@Repository
|
||||
public interface ContactPhoneRepository extends CrudRepository<ContactPhone, Long> {
|
||||
ContactPhone findById(long id);
|
||||
ContactPhone findByCustomerId(long id);
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.partialupdate.repository;
|
||||
|
||||
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;
|
||||
|
||||
import com.baeldung.partialupdate.model.Customer;
|
||||
|
||||
@Repository
|
||||
public interface CustomerRepository extends CrudRepository<Customer, Long> {
|
||||
Customer findById(long id);
|
||||
|
||||
@Modifying
|
||||
@Query("update Customer u set u.phone = :phone where u.id = :id")
|
||||
void updatePhone(@Param(value = "id") long id, @Param(value = "phone") String phone);
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.partialupdate.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.partialupdate.model.CustomerStructured;
|
||||
|
||||
@Repository
|
||||
public interface CustomerStructuredRepository extends CrudRepository<CustomerStructured, Long> {
|
||||
CustomerStructured findById(long id);
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
package com.baeldung.partialupdate.service;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.partialupdate.model.ContactPhone;
|
||||
import com.baeldung.partialupdate.model.Customer;
|
||||
import com.baeldung.partialupdate.model.CustomerDto;
|
||||
import com.baeldung.partialupdate.model.CustomerStructured;
|
||||
import com.baeldung.partialupdate.repository.ContactPhoneRepository;
|
||||
import com.baeldung.partialupdate.repository.CustomerRepository;
|
||||
import com.baeldung.partialupdate.repository.CustomerStructuredRepository;
|
||||
import com.baeldung.partialupdate.util.CustomerMapper;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class CustomerService {
|
||||
|
||||
@Autowired
|
||||
CustomerRepository repo;
|
||||
@Autowired
|
||||
CustomerStructuredRepository repo2;
|
||||
@Autowired
|
||||
ContactPhoneRepository repo3;
|
||||
@Autowired
|
||||
CustomerMapper mapper;
|
||||
|
||||
public Customer getCustomer(long id) {
|
||||
return repo.findById(id);
|
||||
}
|
||||
|
||||
public void updateCustomerWithCustomQuery(long id, String phone) {
|
||||
repo.updatePhone(id, phone);
|
||||
}
|
||||
|
||||
public Customer addCustomer(String name) {
|
||||
Customer myCustomer = new Customer();
|
||||
myCustomer.name = name;
|
||||
repo.save(myCustomer);
|
||||
return myCustomer;
|
||||
}
|
||||
|
||||
public Customer updateCustomer(long id, String phone) {
|
||||
Customer myCustomer = repo.findById(id);
|
||||
myCustomer.phone = phone;
|
||||
repo.save(myCustomer);
|
||||
return myCustomer;
|
||||
}
|
||||
|
||||
public Customer addCustomer(CustomerDto dto) {
|
||||
Customer myCustomer = new Customer();
|
||||
mapper.updateCustomerFromDto(dto, myCustomer);
|
||||
repo.save(myCustomer);
|
||||
return myCustomer;
|
||||
}
|
||||
|
||||
public Customer updateCustomer(CustomerDto dto) {
|
||||
Customer myCustomer = repo.findById(dto.getId());
|
||||
mapper.updateCustomerFromDto(dto, myCustomer);
|
||||
repo.save(myCustomer);
|
||||
return myCustomer;
|
||||
}
|
||||
|
||||
public CustomerStructured addCustomerStructured(String name) {
|
||||
CustomerStructured myCustomer = new CustomerStructured();
|
||||
myCustomer.name = name;
|
||||
repo2.save(myCustomer);
|
||||
return myCustomer;
|
||||
}
|
||||
|
||||
public void addCustomerPhone(long customerId, String phone) {
|
||||
ContactPhone myPhone = new ContactPhone();
|
||||
myPhone.phone = phone;
|
||||
myPhone.customerId = customerId;
|
||||
repo3.save(myPhone);
|
||||
}
|
||||
|
||||
public CustomerStructured updateCustomerStructured(long id, String name) {
|
||||
CustomerStructured myCustomer = repo2.findById(id);
|
||||
myCustomer.name = name;
|
||||
repo2.save(myCustomer);
|
||||
return myCustomer;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.partialupdate.util;
|
||||
|
||||
import org.mapstruct.BeanMapping;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.MappingTarget;
|
||||
import org.mapstruct.NullValuePropertyMappingStrategy;
|
||||
|
||||
import com.baeldung.partialupdate.model.Customer;
|
||||
import com.baeldung.partialupdate.model.CustomerDto;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface CustomerMapper {
|
||||
@BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
|
||||
void updateCustomerFromDto(CustomerDto dto, @MappingTarget Customer entity);
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
|
||||
spring.datasource.url=jdbc:h2:mem:baeldung
|
||||
|
||||
# JPA-Schema-Generation
|
||||
# Use below configuration to generate database schema create commands based on the entity models
|
||||
# and export them into the create.sql file
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata
|
||||
#spring.jpa.properties.hibernate.format_sql=true
|
||||
|
||||
spring.jpa.show-sql=true
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
|
||||
#hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.properties.hibernate.id.new_generator_mappings=false
|
@ -0,0 +1,11 @@
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.cache.use_second_level_cache=false
|
||||
hibernate.cache.use_query_cache=false
|
||||
|
||||
spring.datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=sa
|
||||
|
||||
spring.second-datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS
|
||||
spring.second-datasource.username=sa
|
||||
spring.second-datasource.password=sa
|
@ -0,0 +1,13 @@
|
||||
# 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
|
@ -0,0 +1,17 @@
|
||||
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() {
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
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;
|
||||
import com.baeldung.boot.config.PersistenceConfiguration;
|
||||
import com.baeldung.multipledb.PersistenceProductConfiguration;
|
||||
import com.baeldung.multipledb.PersistenceUserConfiguration;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(excludeAutoConfiguration = {
|
||||
PersistenceConfiguration.class,
|
||||
PersistenceUserConfiguration.class,
|
||||
PersistenceProductConfiguration.class })
|
||||
@ContextConfiguration(classes = Application.class)
|
||||
public class SpringJpaContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
@ -0,0 +1,545 @@
|
||||
package com.baeldung.boot.daos;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
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.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.boot.daos.user.UserRepository;
|
||||
import com.baeldung.boot.domain.User;
|
||||
|
||||
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.*;
|
||||
|
||||
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(Sort.by(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(Sort.by(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();
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.boot.daos;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.domain.User;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.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);
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.baeldung.boot.daos;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.domain.User;
|
||||
import com.baeldung.util.BaeldungPostgresqlContainer;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
@ActiveProfiles({"tc", "tc-auto"})
|
||||
public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon {
|
||||
|
||||
@ClassRule
|
||||
public static PostgreSQLContainer<BaeldungPostgresqlContainer> postgreSQLContainer = BaeldungPostgresqlContainer.getInstance();
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_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));
|
||||
userRepository.flush();
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package com.baeldung.boot.daos;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.domain.User;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.util.TestPropertyValues;
|
||||
import org.springframework.context.ApplicationContextInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
@ActiveProfiles("tc")
|
||||
@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class})
|
||||
public class UserRepositoryTCLiveTest extends UserRepositoryCommon {
|
||||
|
||||
@ClassRule
|
||||
public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1")
|
||||
.withDatabaseName("integration-tests-db")
|
||||
.withUsername("sa")
|
||||
.withPassword("sa");
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_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));
|
||||
userRepository.flush();
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
|
||||
static class Initializer
|
||||
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
|
||||
TestPropertyValues.of(
|
||||
"spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(),
|
||||
"spring.datasource.username=" + postgreSQLContainer.getUsername(),
|
||||
"spring.datasource.password=" + postgreSQLContainer.getPassword()
|
||||
).applyTo(configurableApplicationContext.getEnvironment());
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,252 @@
|
||||
package com.baeldung.boot.services;
|
||||
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
import com.baeldung.boot.services.IOperations;
|
||||
import com.baeldung.util.IDUtil;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public abstract class AbstractServicePersistenceIntegrationTest<T extends Serializable> {
|
||||
|
||||
// tests
|
||||
|
||||
// find - one
|
||||
|
||||
@Test
|
||||
/**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() {
|
||||
// When
|
||||
final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong());
|
||||
|
||||
// Then
|
||||
assertNull(createdResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
getApi().findOne(existingResource.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() {
|
||||
getApi().findOne(IDUtil.randomPositiveLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
final Foo retrievedResource = getApi().findOne(existingResource.getId());
|
||||
assertNotNull(retrievedResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
final Foo retrievedResource = getApi().findOne(existingResource.getId());
|
||||
assertEquals(existingResource, retrievedResource);
|
||||
}
|
||||
|
||||
// find - one - by name
|
||||
|
||||
// find - all
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenNoExceptions() {
|
||||
getApi().findAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() {
|
||||
final List<Foo> resources = getApi().findAll();
|
||||
|
||||
assertNotNull(resources);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() {
|
||||
persistNewEntity();
|
||||
|
||||
// When
|
||||
final List<Foo> allResources = getApi().findAll();
|
||||
|
||||
// Then
|
||||
assertThat(allResources, not(Matchers.<Foo> empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
final List<Foo> resources = getApi().findAll();
|
||||
|
||||
assertThat(resources, hasItem(existingResource));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() {
|
||||
persistNewEntity();
|
||||
|
||||
// When
|
||||
final List<Foo> allResources = getApi().findAll();
|
||||
|
||||
// Then
|
||||
for (final Foo resource : allResources) {
|
||||
assertNotNull(resource.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// create
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
/**/public void whenNullResourceIsCreated_thenException() {
|
||||
getApi().create(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenNoExceptions() {
|
||||
persistNewEntity();
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenResourceIsRetrievable() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
assertNotNull(getApi().findOne(existingResource.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() {
|
||||
final Foo originalResource = createNewEntity();
|
||||
final Foo savedResource = getApi().create(originalResource);
|
||||
|
||||
assertEquals(originalResource, savedResource);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenResourceWithFailedConstraintsIsCreated_thenException() {
|
||||
final Foo invalidResource = createNewEntity();
|
||||
invalidate(invalidResource);
|
||||
|
||||
getApi().create(invalidResource);
|
||||
}
|
||||
|
||||
/**
|
||||
* -- specific to the persistence engine
|
||||
*/
|
||||
@Test(expected = DataAccessException.class)
|
||||
@Ignore("Hibernate simply ignores the id silently and still saved (tracking this)")
|
||||
public void whenResourceWithIdIsCreated_thenDataAccessException() {
|
||||
final Foo resourceWithId = createNewEntity();
|
||||
resourceWithId.setId(IDUtil.randomPositiveLong());
|
||||
|
||||
getApi().create(resourceWithId);
|
||||
}
|
||||
|
||||
// update
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
/**/public void whenNullResourceIsUpdated_thenException() {
|
||||
getApi().update(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() {
|
||||
// Given
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
// When
|
||||
getApi().update(existingResource);
|
||||
}
|
||||
|
||||
/**
|
||||
* - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException
|
||||
*/
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenResourceIsUpdatedWithFailedConstraints_thenException() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
invalidate(existingResource);
|
||||
|
||||
getApi().update(existingResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() {
|
||||
// Given
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
// When
|
||||
change(existingResource);
|
||||
getApi().update(existingResource);
|
||||
|
||||
final Foo updatedResource = getApi().findOne(existingResource.getId());
|
||||
|
||||
// Then
|
||||
assertEquals(existingResource, updatedResource);
|
||||
}
|
||||
|
||||
// delete
|
||||
|
||||
// @Test(expected = RuntimeException.class)
|
||||
// public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() {
|
||||
// // When
|
||||
// getApi().delete(IDUtil.randomPositiveLong());
|
||||
// }
|
||||
//
|
||||
// @Test(expected = RuntimeException.class)
|
||||
// public void whenResourceIsDeletedByNegativeId_thenException() {
|
||||
// // When
|
||||
// getApi().delete(IDUtil.randomNegativeLong());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() {
|
||||
// // Given
|
||||
// final Foo existingResource = persistNewEntity();
|
||||
//
|
||||
// // When
|
||||
// getApi().delete(existingResource.getId());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() {
|
||||
// // Given
|
||||
// final Foo existingResource = persistNewEntity();
|
||||
//
|
||||
// // When
|
||||
// getApi().delete(existingResource.getId());
|
||||
//
|
||||
// // Then
|
||||
// assertNull(getApi().findOne(existingResource.getId()));
|
||||
// }
|
||||
|
||||
// template method
|
||||
|
||||
protected Foo createNewEntity() {
|
||||
return new Foo(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
protected abstract IOperations<Foo> getApi();
|
||||
|
||||
private final void invalidate(final Foo entity) {
|
||||
entity.setName(null);
|
||||
}
|
||||
|
||||
private final void change(final Foo entity) {
|
||||
entity.setName(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
protected Foo persistNewEntity() {
|
||||
return getApi().create(createNewEntity());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package com.baeldung.boot.services;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.junit.Ignore;
|
||||
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.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes=Application.class)
|
||||
public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest<Foo> {
|
||||
|
||||
@Autowired
|
||||
private IFooService service;
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenContextIsBootstrapped_thenNoExceptions() {
|
||||
//
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenEntityIsCreated_thenNoExceptions() {
|
||||
service.create(new Foo(randomAlphabetic(6)));
|
||||
}
|
||||
|
||||
@Test(expected = DataIntegrityViolationException.class)
|
||||
public final void whenInvalidEntityIsCreated_thenDataException() {
|
||||
service.create(new Foo());
|
||||
}
|
||||
|
||||
@Test(expected = DataIntegrityViolationException.class)
|
||||
public final void whenEntityWithLongNameIsCreated_thenDataException() {
|
||||
service.create(new Foo(randomAlphabetic(2048)));
|
||||
}
|
||||
|
||||
// custom Query method
|
||||
|
||||
@Test
|
||||
public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() {
|
||||
final String name = randomAlphabetic(6);
|
||||
service.create(new Foo(name));
|
||||
|
||||
final Foo retrievedByName = service.retrieveByName(name);
|
||||
assertNotNull(retrievedByName);
|
||||
}
|
||||
|
||||
// work in progress
|
||||
|
||||
@Test(expected = InvalidDataAccessApiUsageException.class)
|
||||
@Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail")
|
||||
public final void whenSameEntityIsCreatedTwice_thenDataException() {
|
||||
final Foo entity = new Foo(randomAlphabetic(8));
|
||||
service.create(entity);
|
||||
service.create(entity);
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
protected final IOperations<Foo> getApi() {
|
||||
return service;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package com.baeldung.boot.services;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes=Application.class)
|
||||
public class SpringDataJPABarAuditIntegrationTest {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
logger.info("setUpBeforeClass()");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownAfterClass() throws Exception {
|
||||
logger.info("tearDownAfterClass()");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
@Qualifier("barSpringDataJpaService")
|
||||
private IBarService barService;
|
||||
|
||||
@Autowired
|
||||
private EntityManagerFactory entityManagerFactory;
|
||||
|
||||
private EntityManager em;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger.info("setUp()");
|
||||
em = entityManagerFactory.createEntityManager();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
logger.info("tearDown()");
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "tutorialuser")
|
||||
public final void whenBarsModified_thenBarsAudited() {
|
||||
Bar bar = new Bar("BAR1");
|
||||
barService.create(bar);
|
||||
assertEquals(bar.getCreatedDate(), bar.getModifiedDate());
|
||||
assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy());
|
||||
bar.setName("BAR2");
|
||||
bar = barService.update(bar);
|
||||
assertTrue(bar.getCreatedDate() < bar.getModifiedDate());
|
||||
assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy());
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.baeldung.elementcollection;
|
||||
|
||||
import com.baeldung.elementcollection.model.Employee;
|
||||
import com.baeldung.elementcollection.model.Phone;
|
||||
import com.baeldung.elementcollection.repository.EmployeeRepository;
|
||||
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.hamcrest.core.Is.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ElementCollectionApplication.class)
|
||||
public class ElementCollectionIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private EmployeeRepository employeeRepository;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
Employee employee = new Employee(1, "Fred");
|
||||
employee.setPhones(
|
||||
Arrays.asList(new Phone("work", "+55", "99999-9999"), new Phone("home", "+55", "98888-8888")));
|
||||
employeeRepository.save(employee);
|
||||
}
|
||||
|
||||
@After
|
||||
public void clean() {
|
||||
employeeRepository.remove(1);
|
||||
}
|
||||
|
||||
@Test(expected = org.hibernate.LazyInitializationException.class)
|
||||
public void whenAccessLazyCollection_thenThrowLazyInitializationException() {
|
||||
Employee employee = employeeRepository.findById(1);
|
||||
assertThat(employee.getPhones().size(), is(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseJPAQL_thenFetchResult() {
|
||||
Employee employee = employeeRepository.findByJPQL(1);
|
||||
assertThat(employee.getPhones().size(), is(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseEntityGraph_thenFetchResult() {
|
||||
Employee employee = employeeRepository.findByEntityGraph(1);
|
||||
assertThat(employee.getPhones().size(), is(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenUseTransaction_thenFetchResult() {
|
||||
Employee employee = employeeRepository.findById(1);
|
||||
assertThat(employee.getPhones().size(), is(2));
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
package com.baeldung.multipledb;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
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.dao.DataIntegrityViolationException;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.multipledb.dao.product.ProductRepository;
|
||||
import com.baeldung.multipledb.dao.user.PossessionRepository;
|
||||
import com.baeldung.multipledb.dao.user.UserRepository;
|
||||
import com.baeldung.multipledb.model.product.Product;
|
||||
import com.baeldung.multipledb.model.user.PossessionMultipleDB;
|
||||
import com.baeldung.multipledb.model.user.UserMultipleDB;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes=MultipleDbApplication.class)
|
||||
@EnableTransactionManagement
|
||||
public class JpaMultipleDBIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private PossessionRepository possessionRepository;
|
||||
|
||||
@Autowired
|
||||
private ProductRepository productRepository;
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
@Transactional("userTransactionManager")
|
||||
public void whenCreatingUser_thenCreated() {
|
||||
UserMultipleDB user = new UserMultipleDB();
|
||||
user.setName("John");
|
||||
user.setEmail("john@test.com");
|
||||
user.setAge(20);
|
||||
PossessionMultipleDB p = new PossessionMultipleDB("sample");
|
||||
p = possessionRepository.save(p);
|
||||
user.setPossessionList(Collections.singletonList(p));
|
||||
user = userRepository.save(user);
|
||||
final Optional<UserMultipleDB> result = userRepository.findById(user.getId());
|
||||
assertTrue(result.isPresent());
|
||||
System.out.println(result.get().getPossessionList());
|
||||
assertEquals(1, result.get().getPossessionList().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional("userTransactionManager")
|
||||
public void whenCreatingUsersWithSameEmail_thenRollback() {
|
||||
UserMultipleDB user1 = new UserMultipleDB();
|
||||
user1.setName("John");
|
||||
user1.setEmail("john@test.com");
|
||||
user1.setAge(20);
|
||||
user1 = userRepository.save(user1);
|
||||
assertTrue(userRepository.findById(user1.getId()).isPresent());
|
||||
|
||||
UserMultipleDB user2 = new UserMultipleDB();
|
||||
user2.setName("Tom");
|
||||
user2.setEmail("john@test.com");
|
||||
user2.setAge(10);
|
||||
try {
|
||||
user2 = userRepository.save(user2);
|
||||
userRepository.flush();
|
||||
fail("DataIntegrityViolationException should be thrown!");
|
||||
} catch (final DataIntegrityViolationException e) {
|
||||
// Expected
|
||||
} catch (final Exception e) {
|
||||
fail("DataIntegrityViolationException should be thrown, instead got: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional("productTransactionManager")
|
||||
public void whenCreatingProduct_thenCreated() {
|
||||
Product product = new Product();
|
||||
product.setName("Book");
|
||||
product.setId(2);
|
||||
product.setPrice(20);
|
||||
product = productRepository.save(product);
|
||||
|
||||
assertTrue(productRepository.findById(product.getId()).isPresent());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,144 @@
|
||||
package com.baeldung.multipledb;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
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.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.multipledb.PersistenceProductConfiguration;
|
||||
import com.baeldung.multipledb.dao.product.ProductRepository;
|
||||
import com.baeldung.multipledb.model.product.Product;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes=MultipleDbApplication.class)
|
||||
@EnableTransactionManagement
|
||||
public class ProductRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ProductRepository productRepository;
|
||||
|
||||
@Before
|
||||
@Transactional("productTransactionManager")
|
||||
public void setUp() {
|
||||
productRepository.save(Product.from(1001, "Book", 21));
|
||||
productRepository.save(Product.from(1002, "Coffee", 10));
|
||||
productRepository.save(Product.from(1003, "Jeans", 30));
|
||||
productRepository.save(Product.from(1004, "Shirt", 32));
|
||||
productRepository.save(Product.from(1005, "Bacon", 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() {
|
||||
Pageable pageRequest = PageRequest.of(0, 2);
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(2));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1001, 1002)
|
||||
.contains(id)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() {
|
||||
Pageable pageRequest = PageRequest.of(1, 2);
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(2));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1003, 1004)
|
||||
.contains(id)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingLastPage_ThenReturnLastPageWithRemData() {
|
||||
Pageable pageRequest = PageRequest.of(2, 2);
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(1));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1005)
|
||||
.contains(id)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() {
|
||||
Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name"));
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(3));
|
||||
assertThat(result.getContent()
|
||||
.stream()
|
||||
.map(Product::getId)
|
||||
.collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() {
|
||||
Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price")
|
||||
.descending());
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(3));
|
||||
assertThat(result.getContent()
|
||||
.stream()
|
||||
.map(Product::getId)
|
||||
.collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() {
|
||||
Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price")
|
||||
.descending()
|
||||
.and(Sort.by("name")));
|
||||
|
||||
Page<Product> result = productRepository.findAll(pageRequest);
|
||||
|
||||
assertThat(result.getContent(), hasSize(5));
|
||||
assertThat(result.getContent()
|
||||
.stream()
|
||||
.map(Product::getId)
|
||||
.collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() {
|
||||
Pageable pageRequest = PageRequest.of(0, 2);
|
||||
|
||||
List<Product> result = productRepository.findAllByPrice(10, pageRequest);
|
||||
|
||||
assertThat(result, hasSize(2));
|
||||
assertTrue(result.stream()
|
||||
.map(Product::getId)
|
||||
.allMatch(id -> Arrays.asList(1002, 1005)
|
||||
.contains(id)));
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("quoted-lower-case-naming-strategy.properties")
|
||||
class QuotedLowerCaseNamingStrategyH2IntegrationTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Unexpected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Expected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties")
|
||||
class QuotedLowerCaseNamingStrategyPostgresLiveTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Expected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("quoted-upper-case-naming-strategy.properties")
|
||||
class QuotedUpperCaseNamingStrategyH2IntegrationTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Expected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties")
|
||||
class QuotedUpperCaseNamingStrategyPostgresLiveTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Unexpected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Expected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("spring-physical-naming-strategy.properties")
|
||||
class SpringPhysicalNamingStrategyH2IntegrationTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Unexpected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Unexpected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties")
|
||||
class SpringPhysicalNamingStrategyPostgresLiveTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Expected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("unquoted-lower-case-naming-strategy.properties")
|
||||
class UnquotedLowerCaseNamingStrategyH2IntegrationTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Unexpected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Unexpected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties")
|
||||
class UnquotedLowerCaseNamingStrategyPostgresLiveTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Expected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("unquoted-upper-case-naming-strategy.properties")
|
||||
class UnquotedUpperCaseNamingStrategyH2IntegrationTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Expected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.namingstrategy;
|
||||
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class)
|
||||
@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties")
|
||||
class UnquotedUpperCaseNamingStrategyPostgresLiveTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@BeforeEach
|
||||
void insertPeople() {
|
||||
personRepository.saveAll(Arrays.asList(
|
||||
new Person(1L, "John", "Doe"),
|
||||
new Person(2L, "Jane", "Doe"),
|
||||
new Person(3L, "Ted", "Mosby")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"person", "PERSON", "Person"})
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) {
|
||||
Query query = entityManager.createNativeQuery("select * from " + tableName);
|
||||
|
||||
// Expected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"PERSON\"");
|
||||
|
||||
// Unexpected result
|
||||
assertThrows(SQLGrammarException.class, query::getResultStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() {
|
||||
Query query = entityManager.createNativeQuery("select * from \"person\"");
|
||||
|
||||
// Unexpected result
|
||||
List<Person> result = (List<Person>) query.getResultStream()
|
||||
.map(this::fromDatabase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
public Person fromDatabase(Object databaseRow) {
|
||||
Object[] typedDatabaseRow = (Object[]) databaseRow;
|
||||
|
||||
return new Person(
|
||||
((BigInteger) typedDatabaseRow[0]).longValue(),
|
||||
(String) typedDatabaseRow[1],
|
||||
(String) typedDatabaseRow[2]
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.osiv;
|
||||
|
||||
import com.baeldung.osiv.model.BasicUser;
|
||||
import com.baeldung.osiv.repository.BasicUserRepository;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@ActiveProfiles("test")
|
||||
@ContextConfiguration(classes = OsivApplication.class)
|
||||
class UserControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private BasicUserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
BasicUser user = new BasicUser();
|
||||
user.setUsername("root");
|
||||
user.setPermissions(new HashSet<>(Arrays.asList("PERM_READ", "PERM_WRITE")));
|
||||
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTheUserExists_WhenOsivIsEnabled_ThenLazyInitWorkEverywhere() throws Exception {
|
||||
mockMvc.perform(get("/users/root"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.username").value("root"))
|
||||
.andExpect(jsonPath("$.permissions", containsInAnyOrder("PERM_READ", "PERM_WRITE")));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void flushDb() {
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.partialupdate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
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.partialupdate.model.Customer;
|
||||
import com.baeldung.partialupdate.model.CustomerDto;
|
||||
import com.baeldung.partialupdate.model.CustomerStructured;
|
||||
import com.baeldung.partialupdate.service.CustomerService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = PartialUpdateApplication.class)
|
||||
public class PartialUpdateUnitTest {
|
||||
|
||||
@Autowired
|
||||
CustomerService service;
|
||||
|
||||
@Test
|
||||
public void givenCustomer_whenUpdate_thenSuccess() {
|
||||
Customer myCustomer = service.addCustomer("John");
|
||||
myCustomer = service.updateCustomer(myCustomer.id, "+00");
|
||||
assertEquals("+00", myCustomer.phone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomer_whenUpdateWithQuery_thenSuccess() {
|
||||
Customer myCustomer = service.addCustomer("John");
|
||||
service.updateCustomerWithCustomQuery(myCustomer.id, "+88");
|
||||
myCustomer = service.getCustomer(myCustomer.id);
|
||||
assertEquals("+88", myCustomer.phone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomerDto_whenUpdateWithMapper_thenSuccess() {
|
||||
CustomerDto dto = new CustomerDto(new Customer());
|
||||
dto.name = "Johnny";
|
||||
Customer entity = service.addCustomer(dto);
|
||||
|
||||
CustomerDto dto2 = new CustomerDto(entity.id);
|
||||
dto2.phone = "+44";
|
||||
entity = service.updateCustomer(dto2);
|
||||
|
||||
assertEquals("Johnny", entity.name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomerStructured_whenUpdateCustomerPhone_thenSuccess() {
|
||||
CustomerStructured myCustomer = service.addCustomerStructured("John");
|
||||
assertEquals(null, myCustomer.contactPhones);
|
||||
|
||||
service.addCustomerPhone(myCustomer.id, "+44");
|
||||
myCustomer = service.updateCustomerStructured(myCustomer.id, "Mr. John");
|
||||
|
||||
assertNotEquals(null, myCustomer.contactPhones);
|
||||
assertEquals(1, myCustomer.contactPhones.size());
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
|
||||
public class BaeldungPostgresqlContainer extends PostgreSQLContainer<BaeldungPostgresqlContainer> {
|
||||
|
||||
private static final String IMAGE_VERSION = "postgres:11.1";
|
||||
|
||||
private static BaeldungPostgresqlContainer container;
|
||||
|
||||
|
||||
private BaeldungPostgresqlContainer() {
|
||||
super(IMAGE_VERSION);
|
||||
}
|
||||
|
||||
public static BaeldungPostgresqlContainer getInstance() {
|
||||
if (container == null) {
|
||||
container = new BaeldungPostgresqlContainer();
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
super.start();
|
||||
System.setProperty("DB_URL", container.getJdbcUrl());
|
||||
System.setProperty("DB_USERNAME", container.getUsername());
|
||||
System.setProperty("DB_PASSWORD", container.getPassword());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
//do nothing, JVM handles shut down
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public final class IDUtil {
|
||||
|
||||
private IDUtil() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public static String randomPositiveLongAsString() {
|
||||
return Long.toString(randomPositiveLong());
|
||||
}
|
||||
|
||||
public static String randomNegativeLongAsString() {
|
||||
return Long.toString(randomNegativeLong());
|
||||
}
|
||||
|
||||
public static long randomPositiveLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id < 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
private static long randomNegativeLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id > 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.datasource.url=jdbc:h2:mem:baeldung
|
||||
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=root
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=root
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=root
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:h2:mem:spring-strategy
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=root
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=root
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
@ -0,0 +1,9 @@
|
||||
spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql
|
Loading…
x
Reference in New Issue
Block a user