diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java
similarity index 99%
rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java
rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java
index ad6a064c98..51b27ef5f4 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import java.sql.*;
import java.util.UUID;
diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java
similarity index 97%
rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java
rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java
index 27aef8b82f..99e5a1ad4a 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import java.util.Objects;
diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java
similarity index 96%
rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java
rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java
index 5ce196ee47..bbcbb5871e 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.joins;
+package com.baeldung.spring.jdbc.joins;
class ArticleWithAuthor {
diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java
similarity index 98%
rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java
rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java
index 55f03d99ec..48961b786f 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.joins;
+package com.baeldung.spring.jdbc.joins;
import java.sql.Connection;
import java.sql.ResultSet;
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java
similarity index 98%
rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java
index c905482f55..3cb5e779f5 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import org.junit.Before;
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java
similarity index 98%
rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java
rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java
index 387c050285..937cf1b833 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import static org.junit.Assert.*;
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java
similarity index 99%
rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java
index 81179aade9..c13f94f12a 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import org.apache.log4j.Logger;
import org.junit.After;
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java
similarity index 99%
rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java
rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java
index 4e10f8bd43..853e78a68d 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import static org.junit.Assert.assertEquals;
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java
similarity index 99%
rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java
rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java
index 3f69a0e333..055c7ed9ed 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.joins;
+package com.baeldung.spring.jdbc.joins;
import org.junit.After;
import org.junit.Before;
diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml
index 468d50b458..1a5ca8df70 100644
--- a/persistence-modules/pom.xml
+++ b/persistence-modules/pom.xml
@@ -70,6 +70,7 @@
spring-data-jpa-query
spring-data-jpa-query-2
spring-data-jpa-repo
+ spring-data-jpa-repo-2
spring-data-jdbc
@@ -83,8 +84,8 @@
spring-hibernate4
spring-jpa
spring-jpa-2
+ spring-jdbc
- spring-persistence-simple
spring-persistence-simple-2
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java
similarity index 89%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java
rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java
index 1475eccbf0..179dbf2ae7 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java
+++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java
@@ -1,4 +1,4 @@
-package com.baeldung.spring.data.persistence.model;
+package com.baeldung.spring.data.jpa.query;
import javax.persistence.*;
import java.time.LocalDate;
@@ -8,7 +8,6 @@ import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
-
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@@ -28,9 +27,6 @@ public class User {
private Integer status;
- @OneToMany
- List possessionList;
-
public User() {
super();
}
@@ -87,12 +83,20 @@ public class User {
return creationDate;
}
- public List getPossessionList() {
- return possessionList;
+ public LocalDate getLastLoginDate() {
+ return lastLoginDate;
}
- public void setPossessionList(List possessionList) {
- this.possessionList = possessionList;
+ public void setLastLoginDate(LocalDate lastLoginDate) {
+ this.lastLoginDate = lastLoginDate;
+ }
+
+ public boolean isActive() {
+ return active;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
}
@Override
@@ -119,21 +123,4 @@ public class User {
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;
- }
-
}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java
similarity index 65%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java
rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java
index a8e3a536c3..6547e0ef66 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java
+++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java
@@ -1,6 +1,5 @@
-package com.baeldung.spring.data.persistence.repository;
+package com.baeldung.spring.data.jpa.query;
-import com.baeldung.spring.data.persistence.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@@ -9,51 +8,16 @@ import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
-import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
-import java.util.stream.Stream;
public interface UserRepository extends JpaRepository, UserRepositoryCustom {
-
- Stream findAllByName(String name);
-
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection findAllActiveUsers();
- @Query("select u from User u where u.email like '%@gmail.com'")
- List findUsersWithGmailAddress();
-
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
Collection 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 findAllUsers(Sort sort);
@@ -63,6 +27,27 @@ public interface UserRepository extends JpaRepository, UserReposi
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page findAllUsersWithPaginationNative(Pageable pageable);
+ @Query("SELECT u FROM User u WHERE u.status = ?1")
+ User findUserByStatus(Integer status);
+
+ @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
+ User findUserByStatusAndName(Integer status, String name);
+
+ @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 = :status and u.name = :name")
+ User findUserByStatusAndNameNamedParams(@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(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(value = "SELECT u FROM User u WHERE u.name IN :names")
+ List findUserByNameList(@Param("names") Collection names);
+
@Modifying
@Query("update User u set u.status = :status where u.name = :name")
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@@ -74,25 +59,4 @@ public interface UserRepository extends JpaRepository, UserReposi
@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 findUserByNameList(@Param("names") Collection 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();
}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java
similarity index 72%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java
rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java
index 77e661bbbe..a3e53528f7 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java
+++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java
@@ -1,6 +1,4 @@
-package com.baeldung.spring.data.persistence.repository;
-
-import com.baeldung.spring.data.persistence.model.User;
+package com.baeldung.spring.data.jpa.query;
import java.util.Collection;
import java.util.List;
diff --git a/persistence-modules/spring-data-jpa-repo-2/pom.xml b/persistence-modules/spring-data-jpa-repo-2/pom.xml
new file mode 100644
index 0000000000..855b441074
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/pom.xml
@@ -0,0 +1,47 @@
+
+
+ 4.0.0
+
+
+ com.baeldung
+ parent-boot-2
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-2
+
+
+ spring-data-jpa-repo-2
+ spring-data-jpa-repo-2
+
+
+
+
+ javax.persistence
+ javax.persistence-api
+
+
+ org.springframework.data
+ spring-data-jpa
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ com.h2database
+ h2
+
+
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+
+
+ 29.0-jre
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java
similarity index 85%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java
rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java
index 64bfe203d0..6833c4c556 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java
@@ -1,16 +1,10 @@
-package com.baeldung.spring.data.persistence.model;
+package com.baeldung.spring.data.persistence.repository;
+import javax.persistence.*;
import java.io.Serializable;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-
@Entity
public class Foo implements Serializable {
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@@ -28,8 +22,6 @@ public class Foo implements Serializable {
this.name = name;
}
- // API
-
public long getId() {
return id;
}
@@ -46,8 +38,6 @@ public class Foo implements Serializable {
this.name = name;
}
- //
-
@Override
public int hashCode() {
final int prime = 31;
@@ -79,5 +69,4 @@ public class Foo implements Serializable {
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
-
-}
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java
new file mode 100644
index 0000000000..cb09a92b82
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java
@@ -0,0 +1,15 @@
+package com.baeldung.spring.data.persistence.repository;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+public class FooService implements IFooService {
+ @Autowired
+ private IFooDAO dao;
+
+ @Override
+ public Foo create(Foo foo) {
+ return dao.save(foo);
+ }
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java
similarity index 75%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java
rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java
index 0b750e37e1..20a81e7bfa 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java
@@ -1,13 +1,13 @@
package com.baeldung.spring.data.persistence.repository;
-import com.baeldung.spring.data.persistence.model.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
-public interface IFooDao extends JpaRepository {
+public interface IFooDAO extends JpaRepository {
+
+ Foo findByName(String name);
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);
-
}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java
new file mode 100644
index 0000000000..8ce6a2d1ae
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java
@@ -0,0 +1,5 @@
+package com.baeldung.spring.data.persistence.repository;
+
+public interface IFooService {
+ Foo create(Foo foo);
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java
similarity index 90%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java
rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java
index 604923d615..f73ea94658 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java
@@ -1,4 +1,4 @@
-package com.baeldung.spring.data.persistence.config;
+package com.baeldung.spring.data.persistence.repository;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
@@ -20,11 +20,11 @@ import javax.sql.DataSource;
import java.util.Properties;
@Configuration
+@PropertySource("classpath:persistence.properties")
+@ComponentScan("com.baeldung.spring.data.persistence.repository")
+//@ImportResource("classpath*:*springDataConfig.xml")
@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
-@ComponentScan({ "com.baeldung.spring.data.persistence" })
-//@ImportResource("classpath*:*springDataJpaRepositoriesConfig.xml")
-@EnableJpaRepositories("com.baeldung.spring.data.persistence.repository")
+@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository")
public class PersistenceConfig {
@Autowired
@@ -38,7 +38,7 @@ public class PersistenceConfig {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
- em.setPackagesToScan("com.baeldung.spring.data.persistence.model");
+ em.setPackagesToScan("com.baeldung.spring.data.persistence.repository");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
@@ -78,5 +78,4 @@ public class PersistenceConfig {
return hibernateProperties;
}
-
-}
\ No newline at end of file
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties
new file mode 100644
index 0000000000..cb1eab9443
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties
@@ -0,0 +1,3 @@
+spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+spring.datasource.username=sa
+spring.datasource.password=sa
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties
new file mode 100644
index 0000000000..339859a6e8
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties
@@ -0,0 +1,9 @@
+# jdbc.X
+jdbc.driverClassName=org.h2.Driver
+jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+jdbc.user=sa
+jdbc.pass=
+
+# hibernate.X
+hibernate.hbm2ddl.auto=create-drop
+hibernate.dialect=org.hibernate.dialect.H2Dialect
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml
similarity index 82%
rename from persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml
rename to persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml
index 91778a17af..b2616d9eae 100644
--- a/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml
@@ -2,12 +2,10 @@
-
-
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java
new file mode 100644
index 0000000000..141844fa11
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.spring.data.persistence.repository;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@ContextConfiguration(classes = PersistenceConfig.class)
+public class FooServiceIntegrationTest {
+
+ @Autowired
+ private IFooService service;
+
+ @Test(expected = DataIntegrityViolationException.class)
+ public final void whenInvalidEntityIsCreated_thenDataException() {
+ service.create(new Foo());
+ }
+}
diff --git a/persistence-modules/spring-jdbc/pom.xml b/persistence-modules/spring-jdbc/pom.xml
new file mode 100644
index 0000000000..4ac5239318
--- /dev/null
+++ b/persistence-modules/spring-jdbc/pom.xml
@@ -0,0 +1,41 @@
+
+
+ 4.0.0
+
+
+ com.baeldung
+ parent-boot-2
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-2
+
+
+ spring-jdbc
+ spring-jdbc
+
+
+
+ org.springframework.data
+ spring-data-jdbc
+ ${spring-data-jdbc.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-jdbc
+
+
+ com.h2database
+ h2
+
+
+ mysql
+ mysql-connector-java
+ runtime
+
+
+
+
+ 2.0.3.RELEASE
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java
similarity index 95%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java
rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java
index 48ddfb04b1..aa0ffde00c 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java
+++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import java.sql.SQLException;
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java
similarity index 95%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java
rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java
index a43eb265c7..84780e30da 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java
+++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
public class Employee {
private int id;
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java
similarity index 99%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java
rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java
index eef085f386..a6d0fe2f3b 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java
+++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import java.sql.PreparedStatement;
import java.sql.SQLException;
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java
similarity index 94%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java
rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java
index d09cd45dbc..bf55d6160d 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java
+++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java
similarity index 75%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java
rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java
index ddc24e439f..d7eb039637 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java
+++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.config;
+package com.baeldung.spring.jdbc.config;
import javax.sql.DataSource;
@@ -10,12 +10,16 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
-@ComponentScan("com.baeldung.jdbc")
+@ComponentScan("com.baeldung.spring.jdbc")
public class SpringJdbcConfig {
@Bean
public DataSource dataSource() {
- return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("classpath:jdbc/schema.sql").addScript("classpath:jdbc/test-data.sql").build();
+ return new EmbeddedDatabaseBuilder()
+ .setType(EmbeddedDatabaseType.H2)
+ .addScript("classpath:jdbc/schema.sql")
+ .addScript("classpath:jdbc/test-data.sql")
+ .build();
}
// @Bean
diff --git a/persistence-modules/spring-jdbc/src/main/resources/application.properties b/persistence-modules/spring-jdbc/src/main/resources/application.properties
new file mode 100644
index 0000000000..2f09a522ba
--- /dev/null
+++ b/persistence-modules/spring-jdbc/src/main/resources/application.properties
@@ -0,0 +1,3 @@
+spring.datasource.url=jdbc:mysql://localhost:3306/springjdbc
+spring.datasource.username=guest_user
+spring.datasource.password=guest_password
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/jdbc/schema.sql
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql
rename to persistence-modules/spring-jdbc/src/main/resources/jdbc/schema.sql
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/jdbc/test-data.sql
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql
rename to persistence-modules/spring-jdbc/src/main/resources/jdbc/test-data.sql
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java
similarity index 97%
rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java
rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java
index 453656098a..10f47402be 100644
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java
+++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java
@@ -1,9 +1,9 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import java.util.ArrayList;
import java.util.List;
-import com.baeldung.jdbc.config.SpringJdbcConfig;
+import com.baeldung.spring.jdbc.config.SpringJdbcConfig;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/persistence-modules/spring-jpa-2/pom.xml b/persistence-modules/spring-jpa-2/pom.xml
index 08a1f0c6a3..1c21f6b98d 100644
--- a/persistence-modules/spring-jpa-2/pom.xml
+++ b/persistence-modules/spring-jpa-2/pom.xml
@@ -15,6 +15,17 @@
+
+ org.springframework.boot
+ spring-boot-starter
+ ${spring-boot.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+ ${spring-boot.version}
+
+
org.springframework
spring-orm
@@ -43,8 +54,25 @@
h2
${h2.version}
+
+ org.apache.tomcat
+ tomcat-dbcp
+ ${tomcat-dbcp.version}
+
+
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ ${spring-boot.version}
+
org.springframework
spring-test
@@ -57,6 +85,13 @@
5.1.5.RELEASE
+
+
+ 9.0.0.M26
+
+
+ 21.0
+ 2.2.6.RELEASE
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
similarity index 97%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
index 150e3778af..da23803d76 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
@@ -51,7 +51,7 @@ public class HibernateConf {
return transactionManager;
}
- private final Properties hibernateProperties() {
+ private Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java
similarity index 87%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java
index e406f896dc..bd78fe647d 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java
@@ -1,52 +1,49 @@
-package com.baeldung.persistence.dao.common;
-
-import java.io.Serializable;
-import java.util.List;
+package com.baeldung.spring.dao.generics;
+import com.google.common.base.Preconditions;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.common.base.Preconditions;
+import java.io.Serializable;
+import java.util.List;
@SuppressWarnings("unchecked")
-public abstract class AbstractHibernateDao extends AbstractDao implements IOperations {
+public abstract class AbstractHibernateDao {
+ private Class clazz;
@Autowired
protected SessionFactory sessionFactory;
- // API
+ public void setClazz(final Class clazzToSet) {
+ clazz = Preconditions.checkNotNull(clazzToSet);
+ }
- @Override
+ // API
public T findOne(final long id) {
return (T) getCurrentSession().get(clazz, id);
}
- @Override
public List findAll() {
return getCurrentSession().createQuery("from " + clazz.getName()).list();
}
- @Override
public T create(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().saveOrUpdate(entity);
return entity;
}
- @Override
public T update(final T entity) {
Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity);
}
- @Override
public void delete(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().delete(entity);
}
- @Override
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
Preconditions.checkState(entity != null);
@@ -56,5 +53,4 @@ public abstract class AbstractHibernateDao extends Abstr
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
-
}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java
similarity index 96%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java
index a6542c5cb1..e68a9281a0 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java
@@ -1,4 +1,4 @@
-package com.baeldung.jpa.dao;
+package com.baeldung.spring.dao.generics;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@@ -6,7 +6,6 @@ import java.io.Serializable;
import java.util.List;
public abstract class AbstractJpaDAO {
-
private Class clazz;
@PersistenceContext(unitName = "entityManagerFactory")
@@ -42,5 +41,4 @@ public abstract class AbstractJpaDAO {
final T entity = findOne(entityId);
delete(entity);
}
-
}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java
similarity index 82%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java
index 009876f8cb..7849abb25f 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java
@@ -1,21 +1,10 @@
-package com.baeldung.persistence.model;
-
-import java.io.Serializable;
-
-import javax.persistence.Cacheable;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.NamedNativeQueries;
-import javax.persistence.NamedNativeQuery;
+package com.baeldung.spring.dao.generics;
import org.hibernate.annotations.CacheConcurrencyStrategy;
+import javax.persistence.*;
+import java.io.Serializable;
+
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java
new file mode 100644
index 0000000000..4c2014c717
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java
@@ -0,0 +1,21 @@
+package com.baeldung.spring.dao.generics;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+public class FooService implements IFooService {
+
+ IGenericDao dao;
+
+ @Autowired
+ public void setDao(IGenericDao daoToSet) {
+ dao = daoToSet;
+ dao.setClazz(Foo.class);
+ }
+
+ @Override
+ public Foo retrieveByName(String name) {
+ return null;
+ }
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java
similarity index 89%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java
index 18b16fa033..619a144176 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java
@@ -1,11 +1,11 @@
-package com.baeldung.persistence.dao.common;
-
-import java.io.Serializable;
+package com.baeldung.spring.dao.generics;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
+import java.io.Serializable;
+
@Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GenericHibernateDao extends AbstractHibernateDao implements IGenericDao {
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java
similarity index 80%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java
index d4da194f4d..cf89b05f96 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java
@@ -1,12 +1,10 @@
-package com.baeldung.persistence.dao.common;
-
-import java.io.Serializable;
+package com.baeldung.spring.dao.generics;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
-import com.baeldung.jpa.dao.AbstractJpaDAO;
+import java.io.Serializable;
@Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java
new file mode 100644
index 0000000000..2d525de405
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java
@@ -0,0 +1,5 @@
+package com.baeldung.spring.dao.generics;
+
+public interface IFooService {
+ Foo retrieveByName(String name);
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java
similarity index 64%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java
index 34c5e0f616..3fd7baf63f 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java
@@ -1,9 +1,10 @@
-package com.baeldung.persistence.dao.common;
+package com.baeldung.spring.dao.generics;
import java.io.Serializable;
import java.util.List;
-public interface IOperations {
+public interface IGenericDao {
+ void setClazz(Class< T > clazzToSet);
T findOne(final long id);
@@ -16,5 +17,4 @@ public interface IOperations {
void delete(final T entity);
void deleteById(final long entityId);
-
}
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java
new file mode 100644
index 0000000000..c0a99e92c8
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java
@@ -0,0 +1,56 @@
+package com.baeldung.spring.hibernate;
+
+import com.google.common.base.Preconditions;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.io.Serializable;
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public abstract class AbstractHibernateDao {
+ private Class clazz;
+
+ @Autowired
+ protected SessionFactory sessionFactory;
+
+ protected final void setClazz(final Class clazzToSet) {
+ clazz = Preconditions.checkNotNull(clazzToSet);
+ }
+
+ // API
+ public T findOne(final long id) {
+ return (T) getCurrentSession().get(clazz, id);
+ }
+
+ public List findAll() {
+ return getCurrentSession().createQuery("from " + clazz.getName()).list();
+ }
+
+ public T create(final T entity) {
+ Preconditions.checkNotNull(entity);
+ getCurrentSession().saveOrUpdate(entity);
+ return entity;
+ }
+
+ public T update(final T entity) {
+ Preconditions.checkNotNull(entity);
+ return (T) getCurrentSession().merge(entity);
+ }
+
+ public void delete(final T entity) {
+ Preconditions.checkNotNull(entity);
+ getCurrentSession().delete(entity);
+ }
+
+ public void deleteById(final long entityId) {
+ final T entity = findOne(entityId);
+ Preconditions.checkState(entity != null);
+ delete(entity);
+ }
+
+ protected Session getCurrentSession() {
+ return sessionFactory.getCurrentSession();
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java
new file mode 100644
index 0000000000..f92b510071
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java
@@ -0,0 +1,42 @@
+package com.baeldung.spring.hibernate;
+
+import javax.persistence.*;
+import java.io.Serializable;
+
+@Entity
+public class Foo implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ public Foo() {
+ super();
+ }
+
+ public Foo(final String name) {
+ super();
+
+ this.name = name;
+ }
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "ID")
+ private Long id;
+ @Column(name = "NAME")
+ private String name;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(final Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java
similarity index 55%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java
index 67c10fe7fe..d5495d4eb1 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java
@@ -1,14 +1,9 @@
-package com.baeldung.hibernate.dao;
+package com.baeldung.spring.hibernate;
-import com.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
-import com.baeldung.jpa.dao.IFooDao;
-import com.baeldung.persistence.dao.common.AbstractHibernateDao;
-
@Repository
public class FooDao extends AbstractHibernateDao implements IFooDao {
-
public FooDao() {
super();
@@ -16,5 +11,4 @@ public class FooDao extends AbstractHibernateDao implements IFooDao {
}
// API
-
}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java
similarity index 65%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java
index 8140c56edd..d397163be5 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java
@@ -1,21 +1,15 @@
-package com.baeldung.jpa.dao;
+package com.baeldung.spring.hibernate;
import java.util.List;
-import com.baeldung.persistence.model.Foo;
-
public interface IFooDao {
-
Foo findOne(long id);
List findAll();
- Foo create(Foo entity);
-
Foo update(Foo entity);
void delete(Foo entity);
void deleteById(long entityId);
-
}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java
similarity index 91%
rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java
rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java
index e8a2aefd6b..497d735c10 100644
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java
@@ -1,9 +1,8 @@
-package com.baeldung.config;
+package com.baeldung.spring.jpa.guide;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@@ -21,17 +20,12 @@ import java.util.Properties;
@Configuration
@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-h2.properties" })
-@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" })
+@PropertySource("classpath:persistence-h2.properties")
public class PersistenceJPAConfig {
@Autowired
private Environment env;
- public PersistenceJPAConfig() {
- super();
- }
-
// beans
@Bean
@@ -75,9 +69,7 @@ public class PersistenceJPAConfig {
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false");
-
-
+
return hibernateProperties;
}
-
}
\ No newline at end of file
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java
new file mode 100644
index 0000000000..407d8e3394
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java
@@ -0,0 +1,8 @@
+package com.baeldung.spring.transaction;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional
+public class FooService {}
\ No newline at end of file
diff --git a/persistence-modules/spring-jpa-2/src/main/resources/application.properties b/persistence-modules/spring-jpa-2/src/main/resources/application.properties
new file mode 100644
index 0000000000..0270c1683e
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/resources/application.properties
@@ -0,0 +1,11 @@
+# H2
+spring.datasource.driver-class-name=org.h2.Driver
+spring.datasource.username=sa
+spring.datasource.password=
+spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+
+# MySQL
+#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
+#spring.datasource.username=mysqluser
+#spring.datasource.password=mysqlpass
+#spring.datasource.url=jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-jpa-2/src/main/resources/hibernate5Configuration.xml
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml
rename to persistence-modules/spring-jpa-2/src/main/resources/hibernate5Configuration.xml
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties
rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml b/persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml
similarity index 89%
rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml
rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml
index 57687c306d..54774442c6 100644
--- a/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml
+++ b/persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml
@@ -6,7 +6,6 @@
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
-
@@ -14,8 +13,6 @@
-
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-mysql.properties
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties
rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-mysql.properties
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java
rename to persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java
similarity index 100%
rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java
rename to persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java
diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java
similarity index 94%
rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java
rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java
index 99f50abf4c..d1f8864357 100644
--- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java
+++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.autogenkey.config;
+package com.baeldung.spring.jdbc.autogenkey.config;
import javax.sql.DataSource;
diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java
similarity index 92%
rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java
rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java
index cf0dbe4681..0f47473bd7 100644
--- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java
+++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.autogenkey.repository;
+package com.baeldung.spring.jdbc.autogenkey.repository;
import java.sql.PreparedStatement;
diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java
similarity index 90%
rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java
rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java
index 022ea29ed6..247fbf28c2 100644
--- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java
+++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.autogenkey.repository;
+package com.baeldung.spring.jdbc.autogenkey.repository;
import java.util.HashMap;
import java.util.Map;
diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java
similarity index 79%
rename from persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java
rename to persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java
index aa4d061997..f0ad853c2a 100644
--- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java
+++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc.autogenkey;
+package com.baeldung.spring.jdbc.autogenkey;
import static org.junit.Assert.assertEquals;
@@ -9,14 +9,14 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
-import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
-import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
+import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
+import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
@RunWith(SpringRunner.class)
public class GetAutoGenKeyByJDBC {
@Configuration
- @ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey" })
+ @ComponentScan(basePackages = {"com.baeldung.spring.jdbc.autogenkey"})
public static class SpringConfig {
}
diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java
similarity index 95%
rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java
rename to persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java
index bd6fe0fb15..adc2255ca4 100644
--- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java
+++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
public class Employee {
private int id;
diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java
similarity index 98%
rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java
rename to persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java
index 2ea42381eb..6e2ad9682d 100644
--- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java
+++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import java.util.ArrayList;
import java.util.Collections;
diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java
similarity index 99%
rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java
rename to persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java
index 369725bafd..bbc688293b 100644
--- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java
+++ b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.jdbc;
+package com.baeldung.spring.jdbc;
import static org.junit.jupiter.api.Assertions.assertEquals;
diff --git a/persistence-modules/spring-persistence-simple/.gitignore b/persistence-modules/spring-persistence-simple/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/persistence-modules/spring-persistence-simple/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md
deleted file mode 100644
index d665433eef..0000000000
--- a/persistence-modules/spring-persistence-simple/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-=========
-
-## Spring Persistence Example Project
-
-
-### Relevant Articles:
-- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
-- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
-- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
-- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
-- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
-- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
-- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
-- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate)
-- [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation)
-
-### 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
-
diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml
deleted file mode 100644
index 7318ec55bd..0000000000
--- a/persistence-modules/spring-persistence-simple/pom.xml
+++ /dev/null
@@ -1,152 +0,0 @@
-
-
- 4.0.0
- spring-persistence-simple
- 0.1-SNAPSHOT
- spring-persistence-simple
-
-
- com.baeldung
- persistence-modules
- 1.0.0-SNAPSHOT
-
-
-
-
-
- org.springframework
- spring-orm
- ${org.springframework.version}
-
-
- org.springframework
- spring-context
- ${org.springframework.version}
-
-
- org.springframework
- spring-aspects
- ${org.springframework.version}
-
-
-
- org.hibernate
- hibernate-core
- ${hibernate.version}
-
-
- javax.transaction
- jta
- ${jta.version}
-
-
- org.hibernate
- hibernate-entitymanager
- ${hibernate.version}
-
-
- mysql
- mysql-connector-java
- ${mysql-connector-java.version}
- runtime
-
-
- org.springframework.data
- spring-data-jpa
- ${spring-data-jpa.version}
-
-
- com.h2database
- h2
- ${h2.version}
-
-
-
- org.apache.tomcat
- tomcat-dbcp
- ${tomcat-dbcp.version}
-
-
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
- org.assertj
- assertj-core
- ${assertj.version}
-
-
-
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
- test
-
-
-
- org.springframework
- spring-test
- ${org.springframework.version}
- test
-
-
- com.querydsl
- querydsl-jpa
- ${querydsl.version}
-
-
- com.querydsl
- querydsl-apt
- ${querydsl.version}
-
-
-
-
-
-
- com.mysema.maven
- apt-maven-plugin
- ${apt-maven-plugin.version}
-
-
- generate-sources
-
- process
-
-
- target/generated-sources
- com.querydsl.apt.jpa.JPAAnnotationProcessor
-
-
-
-
-
-
-
-
-
- 5.2.6.RELEASE
-
-
- 5.4.13.Final
- 8.0.19
- 1.4.200
- 2.2.7.RELEASE
- 9.0.0.M26
- 1.1
- 4.2.1
-
-
- 21.0
- 3.8.0
- 1.1.3
-
-
-
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java
deleted file mode 100644
index cdddbaa787..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package com.baeldung.config;
-
-import com.baeldung.persistence.service.FooService;
-import com.google.common.base.Preconditions;
-import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.core.env.Environment;
-import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
-import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
-import org.springframework.orm.hibernate5.HibernateTransactionManager;
-import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
-import org.springframework.orm.jpa.JpaTransactionManager;
-import org.springframework.orm.jpa.JpaVendorAdapter;
-import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
-import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-import javax.sql.DataSource;
-import java.util.Properties;
-
-@Configuration
-@EnableTransactionManagement
-@EnableJpaAuditing
-@PropertySource({ "classpath:persistence-mysql.properties" })
-@ComponentScan(basePackages = { "com.baeldung.persistence.dao", "com.baeldung.jpa.dao" })
-public class PersistenceConfig {
-
- @Autowired
- private Environment env;
-
- public PersistenceConfig() {
- super();
- }
-
- @Bean
- public LocalSessionFactoryBean sessionFactory() {
- final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
- sessionFactory.setDataSource(restDataSource());
- sessionFactory.setPackagesToScan("com.baeldung.persistence.model");
- sessionFactory.setHibernateProperties(hibernateProperties());
-
- return sessionFactory;
- }
-
- @Bean
- public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
- final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
- emf.setDataSource(restDataSource());
- emf.setPackagesToScan("com.baeldung.persistence.model");
-
- final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
- emf.setJpaVendorAdapter(vendorAdapter);
- emf.setJpaProperties(hibernateProperties());
-
- return emf;
- }
-
- @Bean
- public DataSource restDataSource() {
- final BasicDataSource dataSource = new BasicDataSource();
- dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
- dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
- dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
- dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
-
- return dataSource;
- }
-
- @Bean
- public PlatformTransactionManager hibernateTransactionManager() {
- final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
- transactionManager.setSessionFactory(sessionFactory().getObject());
- return transactionManager;
- }
-
- @Bean
- public PlatformTransactionManager jpaTransactionManager() {
- final JpaTransactionManager transactionManager = new JpaTransactionManager();
- transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
- return transactionManager;
- }
-
- @Bean
- public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
- return new PersistenceExceptionTranslationPostProcessor();
- }
-
- @Bean
- public FooService fooService() {
- return new FooService();
- }
-
- private Properties hibernateProperties() {
- final Properties hibernateProperties = new Properties();
- hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
- hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
- hibernateProperties.setProperty("hibernate.show_sql", "true");
-
- // Envers properties
- hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
-
- return hibernateProperties;
- }
-
-}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java
deleted file mode 100644
index e79a44a0c2..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.baeldung.jpa.dao;
-
-import com.baeldung.persistence.model.Foo;
-import org.springframework.stereotype.Repository;
-
-@Repository
-public class FooDao extends AbstractJpaDAO implements IFooDao {
-
- public FooDao() {
- super();
-
- setClazz(Foo.class);
- }
-
- // API
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
deleted file mode 100644
index 5a6c76a93a..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.baeldung.persistence.dao.common;
-
-import java.io.Serializable;
-
-import com.google.common.base.Preconditions;
-
-public abstract class AbstractDao implements IOperations {
-
- protected Class clazz;
-
- protected final void setClazz(final Class clazzToSet) {
- clazz = Preconditions.checkNotNull(clazzToSet);
- }
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java
deleted file mode 100644
index 8d8af18394..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.baeldung.persistence.dao.common;
-
-import java.io.Serializable;
-
-public interface IGenericDao extends IOperations {
- //
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java
deleted file mode 100644
index 5a88ecc6cf..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package com.baeldung.persistence.model;
-
-import java.io.Serializable;
-import java.util.List;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
-import javax.persistence.OrderBy;
-
-@Entity
-public class Bar implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private long id;
-
- @Column(nullable = false)
- private String name;
-
- @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
- @OrderBy("name ASC")
- List fooList;
-
- public Bar() {
- super();
- }
-
- public Bar(final String name) {
- super();
-
- this.name = name;
- }
-
- // API
-
- 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;
- }
-
- public List getFooList() {
- return fooList;
- }
-
- public void setFooList(final List fooList) {
- this.fooList = fooList;
- }
-
- //
-
- @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();
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java
deleted file mode 100644
index efe9743670..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.baeldung.persistence.service;
-
-import java.util.List;
-
-import com.baeldung.jpa.dao.IFooDao;
-import com.baeldung.persistence.model.Foo;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service
-@Transactional
-public class FooService {
-
- @Autowired
- private IFooDao dao;
-
- public FooService() {
- super();
- }
-
- // API
-
- public void create(final Foo entity) {
- dao.create(entity);
- }
-
- public Foo findOne(final long id) {
- return dao.findOne(id);
- }
-
- public List findAll() {
- return dao.findAll();
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java
deleted file mode 100644
index 44ca9fc62e..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.baeldung.spring.data.persistence.model;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-@Entity
-@Table
-public class Possession {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private long id;
-
- private String name;
-
- public Possession() {
- super();
- }
-
- public Possession(final String name) {
- super();
-
- this.name = name;
- }
-
- public long getId() {
- return id;
- }
-
- public void setId(final int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(final String name) {
- this.name = name;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = (prime * result) + (int) (id ^ (id >>> 32));
- result = (prime * result) + ((name == null) ? 0 : name.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- final Possession other = (Possession) obj;
- if (id != other.id) {
- return false;
- }
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
- builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
- return builder.toString();
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java
deleted file mode 100644
index 366b2c54d0..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.baeldung.spring.data.persistence.repository;
-
-import com.baeldung.spring.data.persistence.model.User;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.criteria.*;
-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;
-
-public class UserRepositoryCustomImpl implements UserRepositoryCustom {
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Override
- public List findUserByEmails(Set emails) {
- CriteriaBuilder cb = entityManager.getCriteriaBuilder();
- CriteriaQuery query = cb.createQuery(User.class);
- Root user = query.from(User.class);
-
- Path emailPath = user.get("email");
-
- List 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 findAllUsersByPredicates(Collection> predicates) {
- List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
- Stream allUsersStream = allUsers.stream();
- for (java.util.function.Predicate predicate : predicates) {
- allUsersStream = allUsersStream.filter(predicate);
- }
-
- return allUsersStream.collect(Collectors.toList());
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java
deleted file mode 100644
index 00e7ac01e4..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung.spring.data.persistence.service;
-
-import com.baeldung.spring.data.persistence.model.Foo;
-
-import com.baeldung.persistence.dao.common.IOperations;
-
-public interface IFooService extends IOperations {
-
- Foo retrieveByName(String name);
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java
deleted file mode 100644
index 61c7d6fcaa..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.baeldung.spring.data.persistence.service.common;
-
-import java.io.Serializable;
-import java.util.List;
-
-import org.springframework.data.repository.PagingAndSortingRepository;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.baeldung.persistence.dao.common.IOperations;
-import com.google.common.collect.Lists;
-
-@Transactional
-public abstract class AbstractService implements IOperations {
-
- // 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 findAll() {
- return Lists.newArrayList(getDao().findAll());
- }
-
- // 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(T entity) {
- getDao().delete(entity);
- }
-
- @Override
- public void deleteById(long entityId) {
- T entity = findOne(entityId);
- delete(entity);
- }
-
- protected abstract PagingAndSortingRepository getDao();
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java
deleted file mode 100644
index c1406b8602..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.baeldung.spring.data.persistence.service.impl;
-
-
-import com.baeldung.spring.data.persistence.model.Foo;
-import com.baeldung.spring.data.persistence.repository.IFooDao;
-import com.baeldung.spring.data.persistence.service.IFooService;
-import com.baeldung.spring.data.persistence.service.common.AbstractService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.repository.PagingAndSortingRepository;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service
-@Transactional
-public class FooService extends AbstractService implements IFooService {
-
- @Autowired
- private IFooDao dao;
-
- public FooService() {
- super();
- }
-
- // API
-
- @Override
- protected PagingAndSortingRepository getDao() {
- return dao;
- }
-
- // custom methods
-
- @Override
- public Foo retrieveByName(final String name) {
- return dao.retrieveByName(name);
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java
deleted file mode 100644
index 45e72e046d..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java
+++ /dev/null
@@ -1,33 +0,0 @@
-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;
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml
deleted file mode 100644
index 55546a862a..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- ${hibernate.hbm2ddl.auto}
- ${hibernate.dialect}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml
deleted file mode 100644
index e3d7452eb1..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml b/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml
deleted file mode 100644
index ec0dc2469a..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
-
-
- web - %date [%thread] %-5level %logger{36} - %message%n
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql b/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql
deleted file mode 100644
index 9cedb75c37..0000000000
--- a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-DELIMITER //
- CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
- LANGUAGE SQL
- DETERMINISTIC
- SQL SECURITY DEFINER
- BEGIN
- SELECT * FROM foo WHERE name = fooName;
- END //
-DELIMITER ;
-
-
-DELIMITER //
- CREATE PROCEDURE GetAllFoos()
- LANGUAGE SQL
- DETERMINISTIC
- SQL SECURITY DEFINER
- BEGIN
- SELECT * FROM foo;
- END //
-DELIMITER ;
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java
deleted file mode 100644
index fbda459d65..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package com.baeldung.persistence.service;
-
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.hamcrest.Matchers.hasSize;
-import static org.hamcrest.Matchers.lessThan;
-import static org.junit.Assert.assertThat;
-
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Root;
-
-import com.baeldung.config.PersistenceJPAConfig;
-import com.baeldung.persistence.model.Foo;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
-@DirtiesContext
-public class FooPaginationPersistenceIntegrationTest {
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Autowired
- private FooService fooService;
-
- @Before
- public final void before() {
- final int minimalNumberOfEntities = 25;
- if (fooService.findAll().size() <= minimalNumberOfEntities) {
- for (int i = 0; i < minimalNumberOfEntities; i++) {
- fooService.create(new Foo(randomAlphabetic(6)));
- }
- }
- }
-
- // tests
-
- @Test
- public final void whenContextIsBootstrapped_thenNoExceptions() {
- //
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public final void givenEntitiesExist_whenRetrievingFirstPage_thenCorrect() {
- final int pageSize = 10;
-
- final Query query = entityManager.createQuery("From Foo");
- configurePagination(query, 1, pageSize);
-
- // When
- final List fooList = query.getResultList();
-
- // Then
- assertThat(fooList, hasSize(pageSize));
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public final void givenEntitiesExist_whenRetrievingLastPage_thenCorrect() {
- final int pageSize = 10;
- final Query queryTotal = entityManager.createQuery("Select count(f.id) from Foo f");
- final long countResult = (long) queryTotal.getSingleResult();
-
- final Query query = entityManager.createQuery("Select f from Foo as f order by f.id");
- final int lastPage = (int) ((countResult / pageSize) + 1);
- configurePagination(query, lastPage, pageSize);
- final List fooList = query.getResultList();
-
- // Then
- assertThat(fooList, hasSize(lessThan(pageSize + 1)));
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() {
- final int pageSize = 10;
-
- final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name");
- final List fooIds = queryIds.getResultList();
-
- final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids");
- query.setParameter("ids", fooIds.subList(0, pageSize));
-
- final List fooList = query.getResultList();
-
- // Then
- assertThat(fooList, hasSize(pageSize));
- }
-
- @Test
- public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() {
- final int pageSize = 10;
- final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
- final Root from = criteriaQuery.from(Foo.class);
- final CriteriaQuery select = criteriaQuery.select(from);
- final TypedQuery typedQuery = entityManager.createQuery(select);
- typedQuery.setFirstResult(0);
- typedQuery.setMaxResults(pageSize);
- final List fooList = typedQuery.getResultList();
-
- // Then
- assertThat(fooList, hasSize(pageSize));
- }
-
- @Test
- public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions() {
- int pageNumber = 1;
- final int pageSize = 10;
- final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
-
- final CriteriaQuery countQuery = criteriaBuilder.createQuery(Long.class);
- countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class)));
- final Long count = entityManager.createQuery(countQuery).getSingleResult();
-
- final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
- final Root from = criteriaQuery.from(Foo.class);
- final CriteriaQuery select = criteriaQuery.select(from);
-
- TypedQuery typedQuery;
- while (pageNumber < count.intValue()) {
- typedQuery = entityManager.createQuery(select);
- typedQuery.setFirstResult(pageNumber - 1);
- typedQuery.setMaxResults(pageSize);
- System.out.println("Current page: " + typedQuery.getResultList());
- pageNumber += pageSize;
- }
-
- }
-
- // UTIL
-
- final int determineLastPage(final int pageSize, final long countResult) {
- return (int) (countResult / pageSize) + 1;
- }
-
- final void configurePagination(final Query query, final int pageNumber, final int pageSize) {
- query.setFirstResult((pageNumber - 1) * pageSize);
- query.setMaxResults(pageSize);
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
deleted file mode 100644
index f4b70a7fde..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.baeldung.persistence.service;
-
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-
-import com.baeldung.config.PersistenceJPAConfig;
-import com.baeldung.persistence.model.Foo;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataAccessException;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.InvalidDataAccessApiUsageException;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
-@DirtiesContext
-public class FooServicePersistenceIntegrationTest {
-
- @Autowired
- private FooService 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(randomAlphabetic(2048)));
- }
-
- @Test(expected = DataIntegrityViolationException.class)
- public final void whenEntityWithLongNameIsCreated_thenDataException() {
- service.create(new Foo(randomAlphabetic(2048)));
- }
-
- @Test(expected = InvalidDataAccessApiUsageException.class)
- public final void whenSameEntityIsCreatedTwice_thenDataException() {
- final Foo entity = new Foo(randomAlphabetic(8));
- service.create(entity);
- service.create(entity);
- }
-
- @Test(expected = DataAccessException.class)
- public final void temp_whenInvalidEntityIsCreated_thenDataException() {
- service.create(new Foo(randomAlphabetic(2048)));
- }
-
- @Test
- public final void whenEntityIsCreated_thenFound() {
- final Foo fooEntity = new Foo("abc");
- service.create(fooEntity);
- final Foo found = service.findOne(fooEntity.getId());
- Assert.assertNotNull(found);
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java
deleted file mode 100644
index c3db45ab41..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-package com.baeldung.persistence.service;
-
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Root;
-
-import com.baeldung.config.PersistenceJPAConfig;
-import com.baeldung.persistence.model.Bar;
-import com.baeldung.persistence.model.Foo;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
-@DirtiesContext
-@SuppressWarnings("unchecked")
-public class FooServiceSortingIntegrationTest {
-
- @PersistenceContext
- private EntityManager entityManager;
-
- // tests
-
- @Test
- public final void whenSortingByOneAttributeDefaultOrder_thenPrintSortedResult() {
- final String jql = "Select f from Foo as f order by f.id";
- final Query sortQuery = entityManager.createQuery(jql);
- final List fooList = sortQuery.getResultList();
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
- }
- }
-
- @Test
- public final void whenSortingByOneAttributeSetOrder_thenSortedPrintResult() {
- final String jql = "Select f from Foo as f order by f.id desc";
- final Query sortQuery = entityManager.createQuery(jql);
- final List fooList = sortQuery.getResultList();
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
- }
- }
-
- @Test
- public final void whenSortingByTwoAttributes_thenPrintSortedResult() {
- final String jql = "Select f from Foo as f order by f.name asc, f.id desc";
- final Query sortQuery = entityManager.createQuery(jql);
- final List fooList = sortQuery.getResultList();
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
- }
- }
-
- @Test
- public final void whenSortingFooByBar_thenBarsSorted() {
- final String jql = "Select f from Foo as f order by f.name, f.bar.id";
- final Query barJoinQuery = entityManager.createQuery(jql);
- final List fooList = barJoinQuery.getResultList();
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName());
- if (foo.getBar() != null) {
- System.out.print("-------BarId:" + foo.getBar().getId());
- }
- }
- }
-
- @Test
- public final void whenSortinfBar_thenPrintBarsSortedWithFoos() {
- final String jql = "Select b from Bar as b order by b.id";
- final Query barQuery = entityManager.createQuery(jql);
- final List barList = barQuery.getResultList();
- for (final Bar bar : barList) {
- System.out.println("Bar Id:" + bar.getId());
- for (final Foo foo : bar.getFooList()) {
- System.out.println("FooName:" + foo.getName());
- }
- }
- }
-
- @Test
- public final void whenSortingFooWithCriteria_thenPrintSortedFoos() {
- final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
- final Root from = criteriaQuery.from(Foo.class);
- final CriteriaQuery select = criteriaQuery.select(from);
- criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
- final TypedQuery typedQuery = entityManager.createQuery(select);
- final List fooList = typedQuery.getResultList();
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId());
- }
- }
-
- @Test
- public final void whenSortingFooWithCriteriaAndMultipleAttributes_thenPrintSortedFoos() {
- final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
- final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
- final Root from = criteriaQuery.from(Foo.class);
- final CriteriaQuery select = criteriaQuery.select(from);
- criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id")));
- final TypedQuery typedQuery = entityManager.createQuery(select);
- final List fooList = typedQuery.getResultList();
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
- }
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java
deleted file mode 100644
index 103321fc64..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package com.baeldung.persistence.service;
-
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.junit.Assert.assertNull;
-
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-
-import com.baeldung.config.PersistenceJPAConfig;
-import com.baeldung.persistence.model.Foo;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
-@DirtiesContext
-public class FooServiceSortingWitNullsManualIntegrationTest {
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Autowired
- private FooService service;
-
- // tests
-
- @SuppressWarnings("unchecked")
- @Test
- public final void whenSortingByStringNullLast_thenLastNull() {
- service.create(new Foo());
- service.create(new Foo(randomAlphabetic(6)));
-
- final String jql = "Select f from Foo as f order by f.name desc NULLS LAST";
- final Query sortQuery = entityManager.createQuery(jql);
- final List fooList = sortQuery.getResultList();
- assertNull(fooList.get(fooList.toArray().length - 1).getName());
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName());
- }
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public final void whenSortingByStringNullFirst_thenFirstNull() {
- service.create(new Foo());
-
- final String jql = "Select f from Foo as f order by f.name desc NULLS FIRST";
- final Query sortQuery = entityManager.createQuery(jql);
- final List fooList = sortQuery.getResultList();
- assertNull(fooList.get(0).getName());
- for (final Foo foo : fooList) {
- System.out.println("Name:" + foo.getName());
- }
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java
deleted file mode 100644
index 32a94ea3cb..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package com.baeldung.persistence.service;
-
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.junit.Assert.assertEquals;
-
-import java.util.List;
-
-import com.baeldung.config.PersistenceConfig;
-import com.baeldung.persistence.model.Foo;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.exception.SQLGrammarException;
-import org.hibernate.query.NativeQuery;
-import org.hibernate.query.Query;
-import org.junit.After;
-import org.junit.Assume;
-import org.junit.Before;
-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.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class FooStoredProceduresLiveTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class);
-
- @Autowired
- private SessionFactory sessionFactory;
-
- @Autowired
- private FooService fooService;
-
- private Session session;
-
- @Before
- public final void before() {
- session = sessionFactory.openSession();
- Assume.assumeTrue(getAllFoosExists());
- Assume.assumeTrue(getFoosByNameExists());
- }
-
- private boolean getFoosByNameExists() {
- try {
- @SuppressWarnings("unchecked")
- NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
- sqlQuery.list();
- return true;
- } catch (SQLGrammarException e) {
- LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
- return false;
- }
- }
-
- private boolean getAllFoosExists() {
- try {
- @SuppressWarnings("unchecked")
- NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
- sqlQuery.list();
- return true;
- } catch (SQLGrammarException e) {
- LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
- return false;
- }
- }
-
- @After
- public final void after() {
- session.close();
- }
-
- @Test
- public final void getAllFoosUsingStoredProcedures() {
-
- fooService.create(new Foo(randomAlphabetic(6)));
-
- // Stored procedure getAllFoos using createSQLQuery
- @SuppressWarnings("unchecked")
- NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
- List allFoos = sqlQuery.list();
- for (Foo foo : allFoos) {
- LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
- }
- assertEquals(allFoos.size(), fooService.findAll().size());
-
- // Stored procedure getAllFoos using a Named Query
- @SuppressWarnings("unchecked")
- Query namedQuery = session.getNamedQuery("callGetAllFoos");
- List allFoos2 = namedQuery.list();
- for (Foo foo : allFoos2) {
- LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
- }
- assertEquals(allFoos2.size(), fooService.findAll().size());
- }
-
- @Test
- public final void getFoosByNameUsingStoredProcedures() {
-
- fooService.create(new Foo("NewFooName"));
-
- // Stored procedure getFoosByName using createSQLQuery()
- @SuppressWarnings("unchecked")
- Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
- List allFoosByName = sqlQuery.list();
- for (Foo foo : allFoosByName) {
- LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
- }
-
- // Stored procedure getFoosByName using getNamedQuery()
- @SuppressWarnings("unchecked")
- Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
- List allFoosByName2 = namedQuery.list();
- for (Foo foo : allFoosByName2) {
- LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
- }
-
- }
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java
deleted file mode 100644
index 6f2a499bc5..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java
+++ /dev/null
@@ -1,250 +0,0 @@
-package com.baeldung.persistence.service.transactional;
-
-import com.baeldung.persistence.model.Foo;
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Repository;
-import org.springframework.stereotype.Service;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-import org.springframework.transaction.IllegalTransactionStateException;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-import org.springframework.transaction.support.TransactionTemplate;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceTransactionalTestConfig.class }, loader = AnnotationConfigContextLoader.class)
-@DirtiesContext
-public class FooTransactionalUnitTest {
-
- static abstract class BasicFooDao {
- @PersistenceContext private EntityManager entityManager;
-
- public Foo findOne(final long id) {
- return entityManager.find(Foo.class, id);
- }
-
- public Foo create(final Foo entity) {
- entityManager.persist(entity);
- return entity;
- }
- }
-
- @Repository
- static class RequiredTransactionalFooDao extends BasicFooDao {
- @Override
- @Transactional(propagation = Propagation.REQUIRED)
- public Foo create(Foo entity) {
- return super.create(entity);
- }
- }
-
- @Repository
- static class RequiresNewTransactionalFooDao extends BasicFooDao {
- @Override
- @Transactional(propagation = Propagation.REQUIRES_NEW)
- public Foo create(Foo entity) {
- return super.create(entity);
- }
- }
-
- @Repository
- static class SupportTransactionalFooDao extends BasicFooDao {
- @Override
- @Transactional(propagation = Propagation.SUPPORTS)
- public Foo create(Foo entity) {
- return super.create(entity);
- }
- }
-
- @Repository
- static class MandatoryTransactionalFooDao extends BasicFooDao {
- @Override
- @Transactional(propagation = Propagation.MANDATORY)
- public Foo create(Foo entity) {
- return super.create(entity);
- }
- }
-
- @Repository
- static class SupportTransactionalFooService {
- @Transactional(propagation = Propagation.SUPPORTS)
- public Foo identity(Foo entity) {
- return entity;
- }
- }
-
- @Service
- static class MandatoryTransactionalFooService {
- @Transactional(propagation = Propagation.MANDATORY)
- public Foo identity(Foo entity) {
- return entity;
- }
- }
-
- @Service
- static class NotSupportedTransactionalFooService {
- @Transactional(propagation = Propagation.NOT_SUPPORTED)
- public Foo identity(Foo entity) {
- return entity;
- }
- }
-
- @Service
- static class NeverTransactionalFooService {
- @Transactional(propagation = Propagation.NEVER)
- public Foo identity(Foo entity) {
- return entity;
- }
- }
-
- @Autowired private TransactionTemplate transactionTemplate;
-
- @Autowired private RequiredTransactionalFooDao requiredTransactionalFooDao;
-
- @Autowired private RequiresNewTransactionalFooDao requiresNewTransactionalFooDao;
-
- @Autowired private SupportTransactionalFooDao supportTransactionalFooDao;
-
- @Autowired private MandatoryTransactionalFooDao mandatoryTransactionalFooDao;
-
- @Autowired private MandatoryTransactionalFooService mandatoryTransactionalFooService;
-
- @Autowired private NeverTransactionalFooService neverTransactionalFooService;
-
- @Autowired private NotSupportedTransactionalFooService notSupportedTransactionalFooService;
-
- @Autowired private SupportTransactionalFooService supportTransactionalFooService;
-
- @After
- public void tearDown(){
- PersistenceTransactionalTestConfig.clearSpy();
- }
-
- @Test
- public void givenRequiredWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() {
- requiredTransactionalFooDao.create(new Foo("baeldung"));
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(1, transactionSpy.getCreate());
- }
-
-
-
- @Test
- public void givenRequiresNewWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() {
- requiresNewTransactionalFooDao.create(new Foo("baeldung"));
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(1, transactionSpy.getCreate());
- }
-
- @Test
- public void givenSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() {
- supportTransactionalFooService.identity(new Foo("baeldung"));
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(0, transactionSpy.getCreate());
- }
-
- @Test(expected = IllegalTransactionStateException.class)
- public void givenMandatoryWithNoActiveTransaction_whenCallService_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() {
- mandatoryTransactionalFooService.identity(new Foo("baeldung"));
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(0, transactionSpy.getCreate());
- }
-
- @Test
- public void givenNotSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() {
- notSupportedTransactionalFooService.identity(new Foo("baeldung"));
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(0, transactionSpy.getCreate());
- }
-
- @Test
- public void givenNeverWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() {
- neverTransactionalFooService.identity(new Foo("baeldung"));
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(0, transactionSpy.getCreate());
- }
-
- @Test
- public void givenRequiredWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() {
- transactionTemplate.execute(status -> {
- Foo foo = new Foo("baeldung");
- return requiredTransactionalFooDao.create(foo);
- });
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(1, transactionSpy.getCreate());
- }
-
- @Test
- public void givenRequiresNewWithActiveTransaction_whenCallCreate_thenExpect1NewAnd1Suspend() {
- transactionTemplate.execute(status -> {
- Foo foo = new Foo("baeldung");
- return requiresNewTransactionalFooDao.create(foo);
- });
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(1, transactionSpy.getSuspend());
- Assert.assertEquals(2, transactionSpy.getCreate());
- }
-
- @Test
- public void givenSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() {
- transactionTemplate.execute(status -> {
- Foo foo = new Foo("baeldung");
- return supportTransactionalFooDao.create(foo);
- });
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(1, transactionSpy.getCreate());
- }
-
- @Test
- public void givenMandatoryWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() {
-
- transactionTemplate.execute(status -> {
- Foo foo = new Foo("baeldung");
- return mandatoryTransactionalFooDao.create(foo);
- });
-
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(1, transactionSpy.getCreate());
- }
-
- @Test
- public void givenNotSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd1Suspend() {
- transactionTemplate.execute(status -> {
- Foo foo = new Foo("baeldung");
- return notSupportedTransactionalFooService.identity(foo);
- });
-
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(1, transactionSpy.getSuspend());
- Assert.assertEquals(1, transactionSpy.getCreate());
- }
-
- @Test(expected = IllegalTransactionStateException.class)
- public void givenNeverWithActiveTransaction_whenCallCreate_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() {
- transactionTemplate.execute(status -> {
- Foo foo = new Foo("baeldung");
- return neverTransactionalFooService.identity(foo);
- });
- PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy();
- Assert.assertEquals(0, transactionSpy.getSuspend());
- Assert.assertEquals(1, transactionSpy.getCreate());
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java
deleted file mode 100644
index 72031a2232..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package com.baeldung.persistence.service.transactional;
-
-import com.google.common.base.Preconditions;
-import java.util.Properties;
-import javax.persistence.EntityManagerFactory;
-import javax.sql.DataSource;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.core.env.Environment;
-import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
-import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
-import org.springframework.jdbc.datasource.DriverManagerDataSource;
-import org.springframework.orm.jpa.JpaTransactionManager;
-import org.springframework.orm.jpa.JpaVendorAdapter;
-import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
-import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.TransactionDefinition;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-import org.springframework.transaction.support.DefaultTransactionStatus;
-import org.springframework.transaction.support.TransactionSynchronizationAdapter;
-import org.springframework.transaction.support.TransactionSynchronizationManager;
-import org.springframework.transaction.support.TransactionTemplate;
-
-@Configuration
-@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-h2.properties" })
-@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" })
-@EnableJpaRepositories(basePackages = "com.baeldung.jpa.dao")
-public class PersistenceTransactionalTestConfig {
-
- public static class TransactionSynchronizationAdapterSpy extends TransactionSynchronizationAdapter {
- private int create, suspend;
-
- public int getSuspend() {
- return suspend;
- }
-
- public int getCreate() {
- return create;
- }
-
- public void create() {
- create++;
- }
-
- @Override
- public void suspend() {
- suspend++;
- super.suspend();
- }
- }
-
-
- public static class JpaTransactionManagerSpy extends JpaTransactionManager {
- @Override
- protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) {
- super.prepareSynchronization(status, definition);
- if (status.isNewTransaction()) {
- if ( adapterSpyThreadLocal.get() == null ){
- TransactionSynchronizationAdapterSpy spy = new TransactionSynchronizationAdapterSpy();
- TransactionSynchronizationManager.registerSynchronization(spy);
- adapterSpyThreadLocal.set(spy);
- }
- adapterSpyThreadLocal.get().create();
- }
- }
- }
-
- private static ThreadLocal adapterSpyThreadLocal = new ThreadLocal<>();
-
- @Autowired
- private Environment env;
-
- public PersistenceTransactionalTestConfig() {
- super();
- }
-
- public static TransactionSynchronizationAdapterSpy getSpy(){
- if ( adapterSpyThreadLocal.get() == null )
- return new TransactionSynchronizationAdapterSpy();
- return adapterSpyThreadLocal.get();
- }
-
- public static void clearSpy(){
- adapterSpyThreadLocal.set(null);
- }
-
- // beans
-
- @Bean
- public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
- final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
- em.setDataSource(dataSource());
- em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
-
- final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
- em.setJpaVendorAdapter(vendorAdapter);
- em.setJpaProperties(additionalProperties());
-
- return em;
- }
-
- @Bean
- public DataSource dataSource() {
- final DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
- dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
- dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
- dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
-
- return dataSource;
- }
-
-
-
- @Bean
- public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
- final JpaTransactionManagerSpy transactionManager = new JpaTransactionManagerSpy();
- transactionManager.setEntityManagerFactory(emf);
- return transactionManager;
- }
-
- @Bean
- public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
- return new PersistenceExceptionTranslationPostProcessor();
- }
-
- final Properties additionalProperties() {
- final Properties hibernateProperties = new Properties();
- hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
- hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
- hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false");
- return hibernateProperties;
- }
-
-
- @Bean
- public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager){
- TransactionTemplate template = new TransactionTemplate(transactionManager);
- template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
- return template;
- }
-
-
-}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java
deleted file mode 100644
index 13b5b4357d..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java
+++ /dev/null
@@ -1,555 +0,0 @@
-package com.baeldung.spring.data.persistence.repository;
-
-import com.baeldung.spring.data.persistence.config.PersistenceConfig;
-import com.baeldung.spring.data.persistence.model.User;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.PageRequest;
-import org.springframework.data.domain.Sort;
-import org.springframework.data.jpa.domain.JpaSort;
-import org.springframework.data.mapping.PropertyReferenceException;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-import org.springframework.transaction.annotation.Transactional;
-
-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.*;
-
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
-@DirtiesContext
-public class UserRepositoryCommon {
-
- final String USER_EMAIL = "email@example.com";
- final String USER_EMAIL2 = "email2@example.com";
- final String USER_EMAIL3 = "email3@example.com";
- final String USER_EMAIL4 = "email4@example.com";
- final Integer INACTIVE_STATUS = 0;
- final Integer ACTIVE_STATUS = 1;
- final String USER_EMAIL5 = "email5@example.com";
- final String USER_EMAIL6 = "email6@example.com";
- final String USER_NAME_ADAM = "Adam";
- final String USER_NAME_PETER = "Peter";
-
- @Autowired
- protected UserRepository userRepository;
- @Autowired
- private EntityManager entityManager;
-
- @Test
- @Transactional
- public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() {
- User user1 = new User();
- user1.setName(USER_NAME_ADAM);
- user1.setEmail(USER_EMAIL);
- userRepository.save(user1);
-
- User user2 = new User();
- user2.setName(USER_NAME_ADAM);
- user2.setEmail(USER_EMAIL2);
- userRepository.save(user2);
-
- User user3 = new User();
- user3.setName(USER_NAME_ADAM);
- user3.setEmail(USER_EMAIL3);
- userRepository.save(user3);
-
- User user4 = new User();
- user4.setName("SAMPLE");
- user4.setEmail(USER_EMAIL4);
- userRepository.save(user4);
-
- try (Stream 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 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 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 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 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 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 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 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 emails = new HashSet<>();
- emails.add(USER_EMAIL2);
- emails.add(USER_EMAIL3);
-
- Collection 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 names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER);
-
- List 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 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 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);
-
- System.out.println(TimeZone.getDefault());
-
- List 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 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> predicates = new ArrayList<>();
- predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31)));
- predicates.add(usr -> usr.getEmail().endsWith(".com"));
-
- List 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 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 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();
- }
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java
deleted file mode 100644
index c76e345fdd..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.baeldung.spring.data.persistence.repository;
-
-import com.baeldung.spring.data.persistence.config.PersistenceConfig;
-import com.baeldung.spring.data.persistence.model.User;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.time.LocalDate;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
-@DirtiesContext
-public class UserRepositoryIntegrationTest extends UserRepositoryCommon {
-
- @Test
- @Transactional
- public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
- userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
- userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
- userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS));
- userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS));
- userRepository.flush();
-
- int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE");
-
- assertThat(updatedUsersSize).isEqualTo(2);
- }
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java
deleted file mode 100644
index 2bccada9fe..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java
+++ /dev/null
@@ -1,256 +0,0 @@
-package com.baeldung.spring.data.persistence.service;
-
-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.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-
-import java.io.Serializable;
-import java.util.List;
-
-import com.baeldung.spring.data.persistence.model.Foo;
-import com.baeldung.util.IDUtil;
-import org.hamcrest.Matchers;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.springframework.dao.DataAccessException;
-
-import com.baeldung.persistence.dao.common.IOperations;
-
-public abstract class AbstractServicePersistenceIntegrationTest {
-
- // 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 resources = getApi().findAll();
-
- assertNotNull(resources);
- }
-
- @Test
- /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() {
- persistNewEntity();
-
- // When
- final List allResources = getApi().findAll();
-
- // Then
- assertThat(allResources, not(Matchers. empty()));
- }
-
- @Test
- /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() {
- final Foo existingResource = persistNewEntity();
-
- final List resources = getApi().findAll();
-
- assertThat(resources, hasItem(existingResource));
- }
-
- @Test
- /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() {
- persistNewEntity();
-
- // When
- final List 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 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());
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java
deleted file mode 100644
index 8f628c5615..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.baeldung.spring.data.persistence.service;
-
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.junit.Assert.assertNotNull;
-
-import com.baeldung.spring.data.persistence.model.Foo;
-import com.baeldung.spring.data.persistence.config.PersistenceConfig;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.InvalidDataAccessApiUsageException;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-import com.baeldung.persistence.dao.common.IOperations;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest {
-
- @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 getApi() {
- return service;
- }
-
-}
diff --git a/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore b/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file