From 7ee94d7455955233b462267d99366e0992e6306a Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 28 Sep 2020 23:10:40 +0530 Subject: [PATCH 1/6] JAVA-2432: Moved articles from here to other modules --- .../spring-hibernate4/.gitignore | 15 - .../spring-hibernate4/README.md | 24 -- persistence-modules/spring-hibernate4/pom.xml | 166 ----------- .../hibernate/audit/AuditorAwareImpl.java | 19 -- .../hibernate/criteria/model/Item.java | 81 ------ .../hibernate/fetching/model/OrderDetail.java | 58 ---- .../hibernate/fetching/model/UserEager.java | 71 ----- .../hibernate/fetching/model/UserLazy.java | 71 ----- .../fetching/util/HibernateUtil.java | 29 -- .../fetching/view/FetchingAppView.java | 68 ----- .../persistence/dao/IBarAuditableDao.java | 8 - .../persistence/dao/IBarCrudRepository.java | 10 - .../com/baeldung/persistence/dao/IBarDao.java | 8 - .../baeldung/persistence/dao/IChildDao.java | 8 - .../persistence/dao/IFooAuditableDao.java | 8 - .../com/baeldung/persistence/dao/IFooDao.java | 8 - .../baeldung/persistence/dao/IParentDao.java | 8 - .../persistence/dao/common/AbstractDao.java | 14 - .../common/AbstractHibernateAuditableDao.java | 37 --- .../dao/common/AbstractHibernateDao.java | 59 ---- .../dao/common/AbstractJpaDao.java | 56 ---- .../dao/common/GenericHibernateDao.java | 13 - .../dao/common/IAuditOperations.java | 14 - .../persistence/dao/common/IGenericDao.java | 7 - .../persistence/dao/common/IOperations.java | 20 -- .../persistence/dao/impl/BarAuditableDao.java | 28 -- .../baeldung/persistence/dao/impl/BarDao.java | 19 -- .../persistence/dao/impl/BarJpaDao.java | 19 -- .../persistence/dao/impl/ChildDao.java | 19 -- .../persistence/dao/impl/FooAuditableDao.java | 17 -- .../baeldung/persistence/dao/impl/FooDao.java | 19 -- .../persistence/dao/impl/ParentDao.java | 19 -- .../com/baeldung/persistence/model/Bar.java | 242 ---------------- .../com/baeldung/persistence/model/Child.java | 51 ---- .../com/baeldung/persistence/model/Foo.java | 105 ------- .../baeldung/persistence/model/Parent.java | 60 ---- .../baeldung/persistence/model/Person.java | 31 --- .../service/IBarAuditableService.java | 8 - .../persistence/service/IBarService.java | 8 - .../persistence/service/IChildService.java | 8 - .../service/IFooAuditableService.java | 8 - .../persistence/service/IFooService.java | 8 - .../persistence/service/IParentService.java | 8 - .../AbstractHibernateAuditableService.java | 30 -- .../common/AbstractHibernateService.java | 42 --- .../service/common/AbstractJpaService.java | 42 --- .../service/common/AbstractService.java | 42 --- .../common/AbstractSpringDataJpaService.java | 46 --- .../service/impl/BarAuditableService.java | 41 --- .../service/impl/BarJpaService.java | 30 -- .../persistence/service/impl/BarService.java | 30 -- .../service/impl/BarSpringDataJpaService.java | 26 -- .../service/impl/ChildService.java | 28 -- .../service/impl/FooAuditableService.java | 41 --- .../persistence/service/impl/FooService.java | 30 -- .../service/impl/ParentService.java | 28 -- .../baeldung/spring/PersistenceConfig.java | 186 ------------- .../baeldung/spring/PersistenceXmlConfig.java | 18 -- .../src/main/resources/fetching.cfg.xml | 20 -- .../src/main/resources/fetchingLazy.cfg.xml | 17 -- .../resources/fetching_create_queries.sql | 14 - .../src/main/resources/hibernate4Config.xml | 34 --- .../src/main/resources/immutable.cfg.xml | 38 --- .../src/main/resources/insert_statements.sql | 31 --- .../src/main/resources/logback.xml | 19 -- .../resources/persistence-mysql.properties | 13 - .../src/main/resources/stored_procedure.sql | 20 -- .../src/main/resources/webSecurityConfig.xml | 37 --- .../java/com/baeldung/SpringContextTest.java | 18 -- .../HibernateFetchingIntegrationTest.java | 42 --- .../persistence/IntegrationTestSuite.java | 25 -- .../persistence/audit/AuditTestSuite.java | 14 - .../EnversFooBarAuditIntegrationTest.java | 146 ---------- .../audit/JPABarAuditIntegrationTest.java | 103 ------- .../SpringDataJPABarAuditIntegrationTest.java | 77 ----- .../persistence/hibernate/FooFixtures.java | 101 ------- ...oPaginationPersistenceIntegrationTest.java | 185 ------------- .../FooSortingPersistenceIntegrationTest.java | 174 ------------ .../save/SaveMethodsIntegrationTest.java | 262 ------------------ ...erviceBasicPersistenceIntegrationTest.java | 55 ---- .../FooServicePersistenceIntegrationTest.java | 64 ----- .../service/FooStoredProceduresLiveTest.java | 121 -------- ...rentServicePersistenceIntegrationTest.java | 70 ----- .../spring/config/PersistenceTestConfig.java | 179 ------------ .../src/test/resources/.gitignore | 13 - .../src/test/resources/fetching.cfg.xml | 19 -- .../src/test/resources/fetchingLazy.cfg.xml | 19 -- .../test/resources/persistence-h2.properties | 13 - 88 files changed, 4160 deletions(-) delete mode 100644 persistence-modules/spring-hibernate4/.gitignore delete mode 100644 persistence-modules/spring-hibernate4/README.md delete mode 100644 persistence-modules/spring-hibernate4/pom.xml delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IChildDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IParentDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IOperations.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Child.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Parent.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Person.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IChildService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IParentService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/fetching.cfg.xml delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/fetching_create_queries.sql delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/hibernate4Config.xml delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/immutable.cfg.xml delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/insert_statements.sql delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/logback.xml delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/persistence-mysql.properties delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/stored_procedure.sql delete mode 100644 persistence-modules/spring-hibernate4/src/main/resources/webSecurityConfig.xml delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/SpringContextTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java delete mode 100644 persistence-modules/spring-hibernate4/src/test/resources/.gitignore delete mode 100644 persistence-modules/spring-hibernate4/src/test/resources/fetching.cfg.xml delete mode 100644 persistence-modules/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml delete mode 100644 persistence-modules/spring-hibernate4/src/test/resources/persistence-h2.properties diff --git a/persistence-modules/spring-hibernate4/.gitignore b/persistence-modules/spring-hibernate4/.gitignore deleted file mode 100644 index d31cc4c619..0000000000 --- a/persistence-modules/spring-hibernate4/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear -/target/ -/target/ diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md deleted file mode 100644 index a5a72a9b7e..0000000000 --- a/persistence-modules/spring-hibernate4/README.md +++ /dev/null @@ -1,24 +0,0 @@ -## Spring with Hibernate 4 - -This module contains articles about Spring with Hibernate 4 - -### Relevant Articles: -- [Guide to Hibernate 4 with Spring](https://www.baeldung.com/hibernate-4-spring) -- [Hibernate Pagination](https://www.baeldung.com/hibernate-pagination) -- [Sorting with Hibernate](https://www.baeldung.com/hibernate-sort) -- [Stored Procedures with Hibernate](https://www.baeldung.com/stored-procedures-with-hibernate-tutorial) -- [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) -- [Eager/Lazy Loading In Hibernate](https://www.baeldung.com/hibernate-lazy-eager-loading) -- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) - -### Quick Start - -``` -git clone git://github.com/eugenp/REST.git -cd REST -mvn install -mvn cargo:run -``` - -- **note**: starts on port `8082` - diff --git a/persistence-modules/spring-hibernate4/pom.xml b/persistence-modules/spring-hibernate4/pom.xml deleted file mode 100644 index 3e5a6f913f..0000000000 --- a/persistence-modules/spring-hibernate4/pom.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - 4.0.0 - spring-hibernate4 - 0.1-SNAPSHOT - spring-hibernate4 - - - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../../parent-spring-4 - - - - - - - org.springframework - spring-context - ${org.springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-aspects - ${org.springframework.version} - - - org.springframework.security - spring-security-core - ${org.springframework.security.version} - - - - - - org.springframework - spring-orm - ${org.springframework.version} - - - org.springframework.data - spring-data-jpa - ${org.springframework.data.version} - - - org.hibernate - hibernate-core - ${hibernate.version} - - - org.hibernate - hibernate-envers - ${hibernate-envers.version} - - - javax.transaction - jta - ${jta.version} - - - mysql - mysql-connector-java - ${mysql-connector-java.version} - - - - org.apache.tomcat - tomcat-dbcp - ${tomcat-dbcp.version} - - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - - - - com.google.guava - guava - ${guava.version} - - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - - - org.springframework - spring-test - ${org.springframework.version} - test - - - - org.springframework.security - spring-security-test - ${org.springframework.security.version} - test - - - - org.hsqldb - hsqldb - ${hsqldb.version} - test - - - com.h2database - h2 - ${h2.version} - test - - - - - - - 4.3.4.RELEASE - 4.2.0.RELEASE - 1.10.5.RELEASE - - - 4.3.11.Final - ${hibernate.version} - 5.1.40 - 8.5.8 - 1.1 - 2.3.4 - - - 5.3.3.Final - 2.2.5 - - - 19.0 - - - 2.22.2 - 5.6.2 - 4.13 - - - diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java deleted file mode 100644 index 7aef08b2ce..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.hibernate.audit; - -import java.util.Optional; - -import org.springframework.data.domain.AuditorAware; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; - -public class AuditorAwareImpl implements AuditorAware { - - @Override - public String getCurrentAuditor() { - return Optional.ofNullable(SecurityContextHolder.getContext()) - .map(e -> e.getAuthentication()) - .map(Authentication::getName) - .orElse(null); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java deleted file mode 100644 index 957207b7e6..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.hibernate.criteria.model; - -import java.io.Serializable; - -public class Item implements Serializable { - - private static final long serialVersionUID = 1L; - private Integer itemId; - private String itemName; - private String itemDescription; - private Integer itemPrice; - - // constructors - public Item() { - - } - - public Item(final Integer itemId, final String itemName, final String itemDescription) { - super(); - this.itemId = itemId; - this.itemName = itemName; - this.itemDescription = itemDescription; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((itemId == null) ? 0 : itemId.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 Item other = (Item) obj; - if (itemId == null) { - if (other.itemId != null) - return false; - } else if (!itemId.equals(other.itemId)) - return false; - return true; - } - - public Integer getItemId() { - return itemId; - } - - public void setItemId(final Integer itemId) { - this.itemId = itemId; - } - - public String getItemName() { - return itemName; - } - - public void setItemName(final String itemName) { - this.itemName = itemName; - } - - public String getItemDescription() { - return itemDescription; - } - - public Integer getItemPrice() { - return itemPrice; - } - - public void setItemPrice(final Integer itemPrice) { - this.itemPrice = itemPrice; - } - - public void setItemDescription(final String itemDescription) { - this.itemDescription = itemDescription; - } -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java deleted file mode 100644 index f4a9b8a678..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.hibernate.fetching.model; - -import javax.persistence.*; -import java.io.Serializable; -import java.sql.Date; - -@Entity -@Table(name = "USER_ORDER") -public class OrderDetail implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name = "ORDER_ID") - private Long orderId; - - public OrderDetail() { - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.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; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java deleted file mode 100644 index 9fda4c43bb..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.hibernate.fetching.model; - -import javax.persistence.*; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -@Entity -@Table(name = "USER") -public class UserEager implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name = "USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.EAGER) - private Set orderDetail = new HashSet(); - - public UserEager() { - } - - public UserEager(final Long userId) { - super(); - this.userId = userId; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.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 UserEager other = (UserEager) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(final Long userId) { - this.userId = userId; - } - - public Set getOrderDetail() { - return orderDetail; - } - - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java deleted file mode 100644 index a78eaa4ac0..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.hibernate.fetching.model; - -import javax.persistence.*; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -@Entity -@Table(name = "USER") -public class UserLazy implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name = "USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.LAZY) - private Set orderDetail = new HashSet(); - - public UserLazy() { - } - - public UserLazy(final Long userId) { - super(); - this.userId = userId; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.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 UserLazy other = (UserLazy) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(final Long userId) { - this.userId = userId; - } - - public Set getOrderDetail() { - return orderDetail; - } - - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java deleted file mode 100644 index c7be96abb7..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.hibernate.fetching.util; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.cfg.Configuration; - -public class HibernateUtil { - - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - // two config files are there - // one with lazy loading enabled - // another lazy = false - SessionFactory sf; - if ("lazy".equals(fetchMethod)) { - sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); - } else { - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); - } - - // fetching.cfg.xml is used for this example - return sf.openSession(); - } - - public static Session getHibernateSession() { - return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession(); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java deleted file mode 100644 index 35cdd254e3..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.hibernate.fetching.view; - -import com.baeldung.hibernate.fetching.model.OrderDetail; -import com.baeldung.hibernate.fetching.model.UserEager; -import com.baeldung.hibernate.fetching.model.UserLazy; -import com.baeldung.hibernate.fetching.util.HibernateUtil; -import org.hibernate.Session; -import org.hibernate.Transaction; - -import java.util.List; -import java.util.Set; - -public class FetchingAppView { - - public FetchingAppView() { - - } - - // lazily loaded - public Set lazyLoaded() { - final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); - List users = sessionLazy.createQuery("From UserLazy").list(); - UserLazy userLazyLoaded = users.get(0); - // since data is lazyloaded so data won't be initialized - return (userLazyLoaded.getOrderDetail()); - } - - // eagerly loaded - public Set eagerLoaded() { - final Session sessionEager = HibernateUtil.getHibernateSession(); - // data should be loaded in the following line - // also note the queries generated - List user = sessionEager.createQuery("From UserEager").list(); - UserEager userEagerLoaded = user.get(0); - return userEagerLoaded.getOrderDetail(); - } - - // creates test data - // call this method to create the data in the database - public void createTestData() { - - final Session session = HibernateUtil.getHibernateSession("lazy"); - Transaction tx = session.beginTransaction(); - final UserLazy user1 = new UserLazy(); - final UserLazy user2 = new UserLazy(); - final UserLazy user3 = new UserLazy(); - - session.save(user1); - session.save(user2); - session.save(user3); - - final OrderDetail order1 = new OrderDetail(); - final OrderDetail order2 = new OrderDetail(); - final OrderDetail order3 = new OrderDetail(); - final OrderDetail order4 = new OrderDetail(); - final OrderDetail order5 = new OrderDetail(); - - session.saveOrUpdate(order1); - session.saveOrUpdate(order2); - session.saveOrUpdate(order3); - session.saveOrUpdate(order4); - session.saveOrUpdate(order5); - - tx.commit(); - session.close(); - - } -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java deleted file mode 100644 index 182b493592..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.dao.common.IAuditOperations; -import com.baeldung.persistence.model.Bar; - -public interface IBarAuditableDao extends IBarDao, IAuditOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java deleted file mode 100644 index 4d7db64240..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.persistence.dao; - -import java.io.Serializable; - -import com.baeldung.persistence.model.Bar; -import org.springframework.data.repository.CrudRepository; - -public interface IBarCrudRepository extends CrudRepository { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarDao.java deleted file mode 100644 index 7896a2a84a..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IBarDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.model.Bar; - -public interface IBarDao extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IChildDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IChildDao.java deleted file mode 100644 index a55a0b0598..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IChildDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Child; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IChildDao extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java deleted file mode 100644 index ddbb685988..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.dao.common.IAuditOperations; -import com.baeldung.persistence.model.Foo; - -public interface IFooAuditableDao extends IFooDao, IAuditOperations { - // -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooDao.java deleted file mode 100644 index 0935772dbd..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IFooDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IFooDao extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IParentDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IParentDao.java deleted file mode 100644 index 03680158bb..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/IParentDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Parent; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IParentDao extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java deleted file mode 100644 index 5a6c76a93a..0000000000 --- a/persistence-modules/spring-hibernate4/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-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java deleted file mode 100644 index 41184669ad..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; -import java.util.List; - -import org.hibernate.envers.AuditReader; -import org.hibernate.envers.AuditReaderFactory; -import org.hibernate.envers.query.AuditQuery; - -@SuppressWarnings("unchecked") -public class AbstractHibernateAuditableDao extends AbstractHibernateDao implements IAuditOperations { - - @Override - public List getEntitiesAtRevision(final Number revision) { - final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); - final AuditQuery query = auditReader.createQuery().forEntitiesAtRevision(clazz, revision); - final List resultList = query.getResultList(); - return resultList; - } - - @Override - public List getEntitiesModifiedAtRevision(final Number revision) { - final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); - final AuditQuery query = auditReader.createQuery().forEntitiesModifiedAtRevision(clazz, revision); - final List resultList = query.getResultList(); - return resultList; - } - - @Override - public List getRevisions() { - final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); - final AuditQuery query = auditReader.createQuery().forRevisionsOfEntity(clazz, true, true); - final List resultList = query.getResultList(); - return resultList; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java deleted file mode 100644 index f3ade67f80..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.common.base.Preconditions; - -@SuppressWarnings("unchecked") -public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { - - @Autowired - protected SessionFactory sessionFactory; - - // API - - @Override - 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 void create(final T entity) { - Preconditions.checkNotNull(entity); - getCurrentSession().saveOrUpdate(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); - delete(entity); - } - - protected Session getCurrentSession() { - return sessionFactory.getCurrentSession(); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java deleted file mode 100644 index 69f8e58c25..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -public class AbstractJpaDao extends AbstractDao implements IOperations { - - @PersistenceContext - private EntityManager em; - - // API - - @Override - public T findOne(final long id) { - return em.find(clazz, Long.valueOf(id).intValue()); - } - - @Override - public List findAll() { - final CriteriaBuilder cb = em.getCriteriaBuilder(); - final CriteriaQuery cq = cb.createQuery(clazz); - final Root rootEntry = cq.from(clazz); - final CriteriaQuery all = cq.select(rootEntry); - final TypedQuery allQuery = em.createQuery(all); - return allQuery.getResultList(); - } - - @Override - public void create(final T entity) { - em.persist(entity); - } - - @Override - public T update(final T entity) { - em.merge(entity); - return entity; - } - - @Override - public void delete(final T entity) { - em.remove(entity); - } - - @Override - public void deleteById(final long entityId) { - delete(findOne(entityId)); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java deleted file mode 100644 index 18b16fa033..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Repository; - -@Repository -@Scope(BeanDefinition.SCOPE_PROTOTYPE) -public class GenericHibernateDao extends AbstractHibernateDao implements IGenericDao { - // -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java deleted file mode 100644 index 169d3fed72..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; -import java.util.List; - -public interface IAuditOperations { - - List getEntitiesAtRevision(Number revision); - - List getEntitiesModifiedAtRevision(Number revision); - - List getRevisions(); - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java deleted file mode 100644 index 8d8af18394..0000000000 --- a/persistence-modules/spring-hibernate4/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-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IOperations.java deleted file mode 100644 index 4ef99221ab..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/IOperations.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; -import java.util.List; - -public interface IOperations { - - T findOne(final long id); - - List findAll(); - - void create(final T entity); - - T update(final T entity); - - void delete(final T entity); - - void deleteById(final long entityId); - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java deleted file mode 100644 index e12b6ae2da..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.persistence.dao.impl; - -import java.util.List; - -import com.baeldung.persistence.dao.IBarAuditableDao; -import com.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; -import com.baeldung.persistence.model.Bar; - -public class BarAuditableDao extends AbstractHibernateAuditableDao implements IBarAuditableDao { - - public BarAuditableDao() { - super(); - - setClazz(Bar.class); - } - - // API - - @Override - public List getRevisions() { - final List resultList = super.getRevisions(); - for (final Bar bar : resultList) { - bar.getFooSet().size(); // force FooSet initialization - } - return resultList; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java deleted file mode 100644 index 0ead802dc5..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.persistence.dao.impl; - -import com.baeldung.persistence.dao.common.AbstractHibernateDao; -import com.baeldung.persistence.dao.IBarDao; -import com.baeldung.persistence.model.Bar; -import org.springframework.stereotype.Repository; - -@Repository -public class BarDao extends AbstractHibernateDao implements IBarDao { - - public BarDao() { - super(); - - setClazz(Bar.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java deleted file mode 100644 index e0fa382d41..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.persistence.dao.impl; - -import com.baeldung.persistence.dao.IBarDao; -import com.baeldung.persistence.dao.common.AbstractJpaDao; -import com.baeldung.persistence.model.Bar; -import org.springframework.stereotype.Repository; - -@Repository -public class BarJpaDao extends AbstractJpaDao implements IBarDao { - - public BarJpaDao() { - super(); - - setClazz(Bar.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java deleted file mode 100644 index b55da6e43a..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.persistence.dao.impl; - -import com.baeldung.persistence.dao.common.AbstractHibernateDao; -import com.baeldung.persistence.model.Child; -import com.baeldung.persistence.dao.IChildDao; -import org.springframework.stereotype.Repository; - -@Repository -public class ChildDao extends AbstractHibernateDao implements IChildDao { - - public ChildDao() { - super(); - - setClazz(Child.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java deleted file mode 100644 index 05064c1478..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.persistence.dao.impl; - -import com.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.dao.IFooAuditableDao; - -public class FooAuditableDao extends AbstractHibernateAuditableDao implements IFooAuditableDao { - - public FooAuditableDao() { - super(); - - setClazz(Foo.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java deleted file mode 100644 index 787c449b1d..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.persistence.dao.impl; - -import com.baeldung.persistence.dao.common.AbstractHibernateDao; -import com.baeldung.persistence.dao.IFooDao; -import com.baeldung.persistence.model.Foo; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao extends AbstractHibernateDao implements IFooDao { - - public FooDao() { - super(); - - setClazz(Foo.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java deleted file mode 100644 index 4602b5f30e..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.persistence.dao.impl; - -import com.baeldung.persistence.dao.IParentDao; -import com.baeldung.persistence.dao.common.AbstractHibernateDao; -import com.baeldung.persistence.model.Parent; -import org.springframework.stereotype.Repository; - -@Repository -public class ParentDao extends AbstractHibernateDao implements IParentDao { - - public ParentDao() { - super(); - - setClazz(Parent.class); - } - - // API - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java deleted file mode 100644 index c7f05254cc..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java +++ /dev/null @@ -1,242 +0,0 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; -import java.util.Date; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EntityListeners; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.OneToMany; -import javax.persistence.PrePersist; -import javax.persistence.PreRemove; -import javax.persistence.PreUpdate; - -import org.hibernate.annotations.OrderBy; -import org.hibernate.envers.Audited; -import org.jboss.logging.Logger; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import com.google.common.collect.Sets; - -@Entity -@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") -@Audited -@EntityListeners(AuditingEntityListener.class) -public class Bar implements Serializable { - - private static Logger logger = Logger.getLogger(Bar.class); - - public enum OPERATION { - INSERT, UPDATE, DELETE; - private String value; - - OPERATION() { - value = toString(); - } - - public String getValue() { - return value; - } - - public static OPERATION parse(final String value) { - OPERATION operation = null; - for (final OPERATION op : OPERATION.values()) { - if (op.getValue().equals(value)) { - operation = op; - break; - } - } - return operation; - } - }; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private int id; - - @Column(name = "name") - private String name; - - @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @OrderBy(clause = "NAME DESC") - // @NotAudited - private Set fooSet = Sets.newHashSet(); - - @Column(name = "operation") - private String operation; - - @Column(name = "timestamp") - private long timestamp; - - @Column(name = "created_date", updatable = false, nullable = false) - @CreatedDate - private long createdDate; - - @Column(name = "modified_date") - @LastModifiedDate - private long modifiedDate; - - @Column(name = "created_by") - @CreatedBy - private String createdBy; - - @Column(name = "modified_by") - @LastModifiedBy - private String modifiedBy; - - public Bar() { - super(); - } - - public Bar(final String name) { - super(); - - this.name = name; - } - - // API - - public Set getFooSet() { - return fooSet; - } - - public void setFooSet(final Set fooSet) { - this.fooSet = fooSet; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public OPERATION getOperation() { - return OPERATION.parse(operation); - } - - public void setOperation(final OPERATION operation) { - this.operation = operation.getValue(); - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(final long timestamp) { - this.timestamp = timestamp; - } - - public long getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(final long createdDate) { - this.createdDate = createdDate; - } - - public long getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(final long modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(final String createdBy) { - this.createdBy = createdBy; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(final String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public void setOperation(final String operation) { - this.operation = operation; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Bar other = (Bar) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Bar [name=").append(name).append("]"); - return builder.toString(); - } - - @PrePersist - public void onPrePersist() { - logger.info("@PrePersist"); - audit(OPERATION.INSERT); - } - - @PreUpdate - public void onPreUpdate() { - logger.info("@PreUpdate"); - audit(OPERATION.UPDATE); - } - - @PreRemove - public void onPreRemove() { - logger.info("@PreRemove"); - audit(OPERATION.DELETE); - } - - private void audit(final OPERATION operation) { - setOperation(operation); - setTimestamp((new Date()).getTime()); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Child.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Child.java deleted file mode 100644 index 19cfb2e237..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Child.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToOne; - -@Entity -public class Child implements Serializable { - - @Id - @GeneratedValue - private long id; - - @OneToOne(mappedBy = "child") - private Parent parent; - - public Child() { - super(); - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public Parent getParent() { - return parent; - } - - public void setParent(final Parent parent) { - this.parent = parent; - } - - // - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Child [id=").append(id).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java deleted file mode 100644 index d36a1e58cf..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; - -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.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedNativeQueries; -import javax.persistence.NamedNativeQuery; - -import org.hibernate.envers.Audited; - -@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) -@Entity -@Audited -// @Proxy(lazy = false) -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; - - @Column(name = "name") - private String name; - - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - this.name = name; - } - - // - - public Bar getBar() { - return bar; - } - - public void setBar(final Bar bar) { - this.bar = bar; - } - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - // - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Parent.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Parent.java deleted file mode 100644 index fa6948990b..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Parent.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -@Entity -public class Parent implements Serializable { - - @Id - @GeneratedValue - private long id; - - @OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH }) - @JoinColumn(name = "child_fk") - private Child child; - - public Parent() { - super(); - } - - public Parent(final Child child) { - super(); - - this.child = child; - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public Child getChild() { - return child; - } - - public void setChild(final Child child) { - this.child = child; - } - - // - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Parent [id=").append(id).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Person.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Person.java deleted file mode 100644 index 6a95a7acf5..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Person.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Person { - - @Id - @GeneratedValue - private Long id; - - private String name; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java deleted file mode 100644 index 33e5634d12..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.service; - -import com.baeldung.persistence.dao.common.IAuditOperations; -import com.baeldung.persistence.model.Bar; - -public interface IBarAuditableService extends IBarService, IAuditOperations { - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarService.java deleted file mode 100644 index 21185b5990..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IBarService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.service; - -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.model.Bar; - -public interface IBarService extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IChildService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IChildService.java deleted file mode 100644 index afe67a70c2..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IChildService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.service; - -import com.baeldung.persistence.model.Child; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IChildService extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java deleted file mode 100644 index b787e7fe91..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.service; - -import com.baeldung.persistence.dao.common.IAuditOperations; -import com.baeldung.persistence.model.Foo; - -public interface IFooAuditableService extends IFooService, IAuditOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooService.java deleted file mode 100644 index ffdb53964a..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IFooService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.service; - -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IFooService extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IParentService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IParentService.java deleted file mode 100644 index f941416aac..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/IParentService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.service; - -import com.baeldung.persistence.model.Parent; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IParentService extends IOperations { - // -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java deleted file mode 100644 index 2695d7760a..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import com.baeldung.persistence.dao.common.IAuditOperations; -import com.baeldung.persistence.dao.common.IOperations; -import org.springframework.transaction.annotation.Transactional; - -@Transactional(value = "hibernateTransactionManager") -public abstract class AbstractHibernateAuditableService extends AbstractHibernateService implements IOperations, IAuditOperations { - - @Override - public List getEntitiesAtRevision(final Number revision) { - return getAuditableDao().getEntitiesAtRevision(revision); - } - - @Override - public List getEntitiesModifiedAtRevision(final Number revision) { - return getAuditableDao().getEntitiesModifiedAtRevision(revision); - } - - @Override - public List getRevisions() { - return getAuditableDao().getRevisions(); - } - - abstract protected IAuditOperations getAuditableDao(); - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java deleted file mode 100644 index 02b8ccf48b..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import com.baeldung.persistence.dao.common.IOperations; -import org.springframework.transaction.annotation.Transactional; - -@Transactional(value = "hibernateTransactionManager") -public abstract class AbstractHibernateService extends AbstractService implements IOperations { - - @Override - public T findOne(final long id) { - return super.findOne(id); - } - - @Override - public List findAll() { - return super.findAll(); - } - - @Override - public void create(final T entity) { - super.create(entity); - } - - @Override - public T update(final T entity) { - return super.update(entity); - } - - @Override - public void delete(final T entity) { - super.delete(entity); - } - - @Override - public void deleteById(final long entityId) { - super.deleteById(entityId); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java deleted file mode 100644 index a1c6fe9edf..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import com.baeldung.persistence.dao.common.IOperations; -import org.springframework.transaction.annotation.Transactional; - -@Transactional(value = "jpaTransactionManager") -public abstract class AbstractJpaService extends AbstractService implements IOperations { - - @Override - public T findOne(final long id) { - return super.findOne(id); - } - - @Override - public List findAll() { - return super.findAll(); - } - - @Override - public void create(final T entity) { - super.create(entity); - } - - @Override - public T update(final T entity) { - return super.update(entity); - } - - @Override - public void delete(final T entity) { - super.delete(entity); - } - - @Override - public void deleteById(final long entityId) { - super.deleteById(entityId); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractService.java deleted file mode 100644 index 9b001b1fac..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import com.baeldung.persistence.dao.common.IOperations; - -public abstract class AbstractService implements IOperations { - - @Override - public T findOne(final long id) { - return getDao().findOne(id); - } - - @Override - public List findAll() { - return getDao().findAll(); - } - - @Override - public void create(final T entity) { - getDao().create(entity); - } - - @Override - public T update(final T entity) { - return getDao().update(entity); - } - - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().deleteById(entityId); - } - - protected abstract IOperations getDao(); - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java deleted file mode 100644 index cef483e6bf..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import com.baeldung.persistence.dao.common.IOperations; -import org.springframework.data.repository.CrudRepository; -import org.springframework.transaction.annotation.Transactional; - -import com.google.common.collect.Lists; - -@Transactional(value = "jpaTransactionManager") -public abstract class AbstractSpringDataJpaService implements IOperations { - - @Override - public T findOne(final long id) { - return getDao().findOne(Long.valueOf(id)); - } - - @Override - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - @Override - public void create(final T entity) { - getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().delete(Long.valueOf(entityId)); - } - - protected abstract CrudRepository getDao(); -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java deleted file mode 100644 index d84c28caa5..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import com.baeldung.persistence.dao.common.IAuditOperations; -import com.baeldung.persistence.service.common.AbstractHibernateAuditableService; -import com.baeldung.persistence.dao.IBarAuditableDao; -import com.baeldung.persistence.dao.IBarDao; -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.service.IBarAuditableService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; - -@Service -public class BarAuditableService extends AbstractHibernateAuditableService implements IBarAuditableService { - - @Autowired - @Qualifier("barHibernateDao") - private IBarDao dao; - - @Autowired - @Qualifier("barHibernateAuditableDao") - private IBarAuditableDao auditDao; - - public BarAuditableService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - - @Override - protected IAuditOperations getAuditableDao() { - return auditDao; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java deleted file mode 100644 index 1c1b7a2274..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import com.baeldung.persistence.dao.IBarDao; -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.persistence.service.common.AbstractJpaService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; - -@Service -public class BarJpaService extends AbstractJpaService implements IBarService { - - @Autowired - @Qualifier("barJpaDao") - private IBarDao dao; - - public BarJpaService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarService.java deleted file mode 100644 index 32d1f919c5..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import com.baeldung.persistence.dao.IBarDao; -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.persistence.service.common.AbstractHibernateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; - -@Service -public class BarService extends AbstractHibernateService implements IBarService { - - @Autowired - @Qualifier("barHibernateDao") - private IBarDao dao; - - public BarService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java deleted file mode 100644 index 4a55d08a35..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import java.io.Serializable; - -import com.baeldung.persistence.service.common.AbstractSpringDataJpaService; -import com.baeldung.persistence.dao.IBarCrudRepository; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.service.IBarService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.repository.CrudRepository; - -public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { - - @Autowired - private IBarCrudRepository dao; - - public BarSpringDataJpaService() { - super(); - } - - @Override - protected CrudRepository getDao() { - return dao; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java deleted file mode 100644 index 417fe2c49a..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import com.baeldung.persistence.model.Child; -import com.baeldung.persistence.service.IChildService; -import com.baeldung.persistence.dao.IChildDao; -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.service.common.AbstractHibernateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ChildService extends AbstractHibernateService implements IChildService { - - @Autowired - private IChildDao dao; - - public ChildService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java deleted file mode 100644 index 45ad315c42..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import com.baeldung.persistence.dao.common.IAuditOperations; -import com.baeldung.persistence.service.IFooAuditableService; -import com.baeldung.persistence.service.common.AbstractHibernateAuditableService; -import com.baeldung.persistence.dao.IFooAuditableDao; -import com.baeldung.persistence.dao.IFooDao; -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; - -@Service -public class FooAuditableService extends AbstractHibernateAuditableService implements IFooAuditableService { - - @Autowired - @Qualifier("fooHibernateDao") - private IFooDao dao; - - @Autowired - @Qualifier("fooHibernateAuditableDao") - private IFooAuditableDao auditDao; - - public FooAuditableService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - - @Override - protected IAuditOperations getAuditableDao() { - return auditDao; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java deleted file mode 100644 index 84cf018fee..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import com.baeldung.persistence.dao.IFooDao; -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.service.IFooService; -import com.baeldung.persistence.service.common.AbstractHibernateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; - -@Service -public class FooService extends AbstractHibernateService implements IFooService { - - @Autowired - @Qualifier("fooHibernateDao") - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java deleted file mode 100644 index 078acfc369..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.persistence.service.impl; - -import com.baeldung.persistence.model.Parent; -import com.baeldung.persistence.service.IParentService; -import com.baeldung.persistence.dao.IParentDao; -import com.baeldung.persistence.dao.common.IOperations; -import com.baeldung.persistence.service.common.AbstractHibernateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ParentService extends AbstractHibernateService implements IParentService { - - @Autowired - private IParentDao dao; - - public ParentService() { - super(); - } - - // API - - @Override - protected IOperations getDao() { - return dao; - } - -} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java deleted file mode 100644 index 4927c9957c..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.baeldung.spring; - -import java.util.Properties; - -import javax.sql.DataSource; - -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.domain.AuditorAware; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.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 com.baeldung.hibernate.audit.AuditorAwareImpl; -import com.baeldung.persistence.dao.IBarAuditableDao; -import com.baeldung.persistence.dao.IBarDao; -import com.baeldung.persistence.dao.IFooAuditableDao; -import com.baeldung.persistence.dao.IFooDao; -import com.baeldung.persistence.dao.impl.BarAuditableDao; -import com.baeldung.persistence.dao.impl.BarDao; -import com.baeldung.persistence.dao.impl.BarJpaDao; -import com.baeldung.persistence.dao.impl.FooAuditableDao; -import com.baeldung.persistence.dao.impl.FooDao; -import com.baeldung.persistence.service.IBarAuditableService; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.persistence.service.IFooAuditableService; -import com.baeldung.persistence.service.IFooService; -import com.baeldung.persistence.service.impl.BarAuditableService; -import com.baeldung.persistence.service.impl.BarJpaService; -import com.baeldung.persistence.service.impl.BarSpringDataJpaService; -import com.baeldung.persistence.service.impl.FooAuditableService; -import com.baeldung.persistence.service.impl.FooService; -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") -@EnableJpaAuditing(auditorAwareRef = "auditorProvider") -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.persistence" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean("auditorProvider") - public AuditorAware auditorProvider() { - return new AuditorAwareImpl(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory() { - final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); - emf.setDataSource(restDataSource()); - emf.setPackagesToScan(new String[] { "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 IBarService barJpaService() { - return new BarJpaService(); - } - - @Bean - public IBarService barSpringDataJpaService() { - return new BarSpringDataJpaService(); - } - - @Bean - public IFooService fooHibernateService() { - return new FooService(); - } - - @Bean - public IBarAuditableService barHibernateAuditableService() { - return new BarAuditableService(); - } - - @Bean - public IFooAuditableService fooHibernateAuditableService() { - return new FooAuditableService(); - } - - @Bean - public IBarDao barJpaDao() { - return new BarJpaDao(); - } - - @Bean - public IBarDao barHibernateDao() { - return new BarDao(); - } - - @Bean - public IBarAuditableDao barHibernateAuditableDao() { - return new BarAuditableDao(); - } - - @Bean - public IFooDao fooHibernateDao() { - return new FooDao(); - } - - @Bean - public IFooAuditableDao fooHibernateAuditableDao() { - return new FooAuditableDao(); - } - - private final 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"); - // hibernateProperties.setProperty("hibernate.format_sql", "true"); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "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-hibernate4/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java deleted file mode 100644 index 9cbeb8e1f8..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableTransactionManagement -@ComponentScan({ "com.baeldung.persistence.dao", "com.baeldung.persistence.service" }) -@ImportResource({ "classpath:hibernate4Config.xml" }) -public class PersistenceXmlConfig { - - public PersistenceXmlConfig() { - super(); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/resources/fetching.cfg.xml b/persistence-modules/spring-hibernate4/src/main/resources/fetching.cfg.xml deleted file mode 100644 index 1b9a4a191c..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/fetching.cfg.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/test - root - iamtheking - org.hibernate.dialect.MySQLDialect - true - validate - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml b/persistence-modules/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml deleted file mode 100644 index c5f608e1a7..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/fetchingLazy.cfg.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/test - root - iamtheking - org.hibernate.dialect.MySQLDialect - true - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/resources/fetching_create_queries.sql b/persistence-modules/spring-hibernate4/src/main/resources/fetching_create_queries.sql deleted file mode 100644 index b36d9828f1..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/fetching_create_queries.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE `user` ( - `user_id` int(10) NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`user_id`) -) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ; - - -CREATE TABLE `user_order` ( - `ORDER_ID` int(10) NOT NULL AUTO_INCREMENT, - `USER_ID` int(10) NOT NULL DEFAULT '0', - PRIMARY KEY (`ORDER_ID`,`USER_ID`), - KEY `USER_ID` (`USER_ID`), - CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; - diff --git a/persistence-modules/spring-hibernate4/src/main/resources/hibernate4Config.xml b/persistence-modules/spring-hibernate4/src/main/resources/hibernate4Config.xml deleted file mode 100644 index ca507802cd..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/hibernate4Config.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - ${hibernate.hbm2ddl.auto} - ${hibernate.dialect} - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/resources/immutable.cfg.xml b/persistence-modules/spring-hibernate4/src/main/resources/immutable.cfg.xml deleted file mode 100644 index fe1e3cb723..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/immutable.cfg.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - org.hsqldb.jdbcDriver - jdbc:hsqldb:hsql:mem://localhost/xdb - sa - - - - 1 - - - org.hibernate.dialect.HSQLDialect - - - thread - - - org.hibernate.cache.NoCacheProvider - - - true - - - update - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/resources/insert_statements.sql b/persistence-modules/spring-hibernate4/src/main/resources/insert_statements.sql deleted file mode 100644 index ae008f29bc..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/insert_statements.sql +++ /dev/null @@ -1,31 +0,0 @@ -insert into item (item_id, item_name, item_desc, item_price) -values(1,'item One', 'test 1', 35.12); - -insert into item (item_id, item_name, item_desc, item_price) -values(2,'Pogo stick', 'Pogo stick', 466.12); -insert into item (item_id, item_name, item_desc, item_price) -values(3,'Raft', 'Raft', 345.12); - -insert into item (item_id, item_name, item_desc, item_price) -values(4,'Skate Board', 'Skating', 135.71); - -insert into item (item_id, item_name, item_desc, item_price) -values(5,'Umbrella', 'Umbrella for Rain', 619.25); - -insert into item (item_id, item_name, item_desc, item_price) -values(6,'Glue', 'Glue for home', 432.73); - -insert into item (item_id, item_name, item_desc, item_price) -values(7,'Paint', 'Paint for Room', 1311.40); - -insert into item (item_id, item_name, item_desc, item_price) -values(8,'Red paint', 'Red paint for room', 1135.71); - -insert into item (item_id, item_name, item_desc, item_price) -values(9,'Household Chairs', 'Chairs for house', 25.71); - -insert into item (item_id, item_name, item_desc, item_price) -values(10,'Office Chairs', 'Chairs for office', 395.98); - -insert into item (item_id, item_name, item_desc, item_price) -values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); diff --git a/persistence-modules/spring-hibernate4/src/main/resources/logback.xml b/persistence-modules/spring-hibernate4/src/main/resources/logback.xml deleted file mode 100644 index 56af2d397e..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-hibernate4/src/main/resources/persistence-mysql.properties deleted file mode 100644 index f6b6ab6fca..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/persistence-mysql.properties +++ /dev/null @@ -1,13 +0,0 @@ -# jdbc.X -jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true -jdbc.user=tutorialuser -jdbc.pass=tutorialmy5ql - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop - -# envers.X -envers.audit_table_suffix=_audit_log diff --git a/persistence-modules/spring-hibernate4/src/main/resources/stored_procedure.sql b/persistence-modules/spring-hibernate4/src/main/resources/stored_procedure.sql deleted file mode 100644 index 9cedb75c37..0000000000 --- a/persistence-modules/spring-hibernate4/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-hibernate4/src/main/resources/webSecurityConfig.xml b/persistence-modules/spring-hibernate4/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index e5c19a4ad7..0000000000 --- a/persistence-modules/spring-hibernate4/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index e19965773e..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.spring.PersistenceConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java deleted file mode 100644 index 65bf36f8bf..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.hibernate.fetching; - -import com.baeldung.hibernate.fetching.model.OrderDetail; -import com.baeldung.hibernate.fetching.view.FetchingAppView; -import org.hibernate.Hibernate; -import org.junit.Before; -import org.junit.Test; - -import java.util.Set; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class HibernateFetchingIntegrationTest { - - // this loads sample data in the database - @Before - public void addFecthingTestData() { - FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - } - - // testLazyFetching() tests the lazy loading - // Since it lazily loaded so orderDetalSetLazy won't - // be initialized - @Test - public void testLazyFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetLazy = fav.lazyLoaded(); - assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); - } - - // testEagerFetching() tests the eager loading - // Since it eagerly loaded so orderDetalSetLazy would - // be initialized - @Test - public void testEagerFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetEager = fav.eagerLoaded(); - assertTrue(Hibernate.isInitialized(orderDetalSetEager)); - } -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java deleted file mode 100644 index f5c45a5d6f..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.persistence; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -import com.baeldung.persistence.audit.AuditTestSuite; -import com.baeldung.persistence.hibernate.FooPaginationPersistenceIntegrationTest; -import com.baeldung.persistence.hibernate.FooSortingPersistenceIntegrationTest; -import com.baeldung.persistence.service.FooServiceBasicPersistenceIntegrationTest; -import com.baeldung.persistence.service.FooServicePersistenceIntegrationTest; -import com.baeldung.persistence.service.ParentServicePersistenceIntegrationTest; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ // @formatter:off - AuditTestSuite.class - ,FooServiceBasicPersistenceIntegrationTest.class - ,FooPaginationPersistenceIntegrationTest.class - ,FooServicePersistenceIntegrationTest.class - ,ParentServicePersistenceIntegrationTest.class - ,FooSortingPersistenceIntegrationTest.class - -}) // @formatter:on -public class IntegrationTestSuite { - // -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java deleted file mode 100644 index 34c725d62b..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.persistence.audit; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ // @formatter:off - EnversFooBarAuditIntegrationTest.class, - JPABarAuditIntegrationTest.class, - SpringDataJPABarAuditIntegrationTest.class -}) // @formatter:on -public class AuditTestSuite { - // -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java deleted file mode 100644 index 444324dafc..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.baeldung.persistence.audit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.service.IBarAuditableService; -import com.baeldung.persistence.service.IFooAuditableService; -import com.baeldung.spring.config.PersistenceTestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) -public class EnversFooBarAuditIntegrationTest { - - private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - logger.info("setUpBeforeClass()"); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - logger.info("tearDownAfterClass()"); - } - - @Autowired - @Qualifier("fooHibernateAuditableService") - private IFooAuditableService fooService; - - @Autowired - @Qualifier("barHibernateAuditableService") - private IBarAuditableService barService; - - @Autowired - private SessionFactory sessionFactory; - - private Session session; - - @Before - public void setUp() throws Exception { - logger.info("setUp()"); - makeRevisions(); - session = sessionFactory.openSession(); - } - - @After - public void tearDown() throws Exception { - logger.info("tearDown()"); - session.close(); - } - - private void makeRevisions() { - final Bar bar = rev1(); - rev2(bar); - rev3(bar); - rev4(bar); - } - - // REV #1: insert BAR & FOO1 - private Bar rev1() { - final Bar bar = new Bar("BAR"); - final Foo foo1 = new Foo("FOO1"); - foo1.setBar(bar); - fooService.create(foo1); - return bar; - } - - // REV #2: insert FOO2 & update BAR - private void rev2(final Bar bar) { - final Foo foo2 = new Foo("FOO2"); - foo2.setBar(bar); - fooService.create(foo2); - } - - // REV #3: update BAR - private void rev3(final Bar bar) { - - bar.setName("BAR1"); - barService.update(bar); - } - - // REV #4: insert FOO3 & update BAR - private void rev4(final Bar bar) { - - final Foo foo3 = new Foo("FOO3"); - foo3.setBar(bar); - fooService.create(foo3); - } - - @Test - public final void whenFooBarsModified_thenFooBarsAudited() { - - List barRevisionList; - List fooRevisionList; - - // test Bar revisions - - barRevisionList = barService.getRevisions(); - - assertNotNull(barRevisionList); - assertEquals(4, barRevisionList.size()); - - assertEquals("BAR", barRevisionList.get(0).getName()); - assertEquals("BAR", barRevisionList.get(1).getName()); - assertEquals("BAR1", barRevisionList.get(2).getName()); - assertEquals("BAR1", barRevisionList.get(3).getName()); - - assertEquals(1, barRevisionList.get(0).getFooSet().size()); - assertEquals(2, barRevisionList.get(1).getFooSet().size()); - assertEquals(2, barRevisionList.get(2).getFooSet().size()); - assertEquals(3, barRevisionList.get(3).getFooSet().size()); - - // test Foo revisions - - fooRevisionList = fooService.getRevisions(); - assertNotNull(fooRevisionList); - assertEquals(3, fooRevisionList.size()); - assertEquals("FOO1", fooRevisionList.get(0).getName()); - assertEquals("FOO2", fooRevisionList.get(1).getName()); - assertEquals("FOO3", fooRevisionList.get(2).getName()); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java deleted file mode 100644 index 733074a6a3..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.baeldung.persistence.audit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Bar.OPERATION; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.spring.config.PersistenceTestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class JPABarAuditIntegrationTest { - - private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - logger.info("setUpBeforeClass()"); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - logger.info("tearDownAfterClass()"); - } - - @Autowired - @Qualifier("barJpaService") - private IBarService barService; - - @Autowired - private EntityManagerFactory entityManagerFactory; - - private EntityManager em; - - @Before - public void setUp() throws Exception { - logger.info("setUp()"); - em = entityManagerFactory.createEntityManager(); - } - - @After - public void tearDown() throws Exception { - logger.info("tearDown()"); - em.close(); - } - - @Test - public final void whenBarsModified_thenBarsAudited() { - - // insert BAR1 - Bar bar1 = new Bar("BAR1"); - barService.create(bar1); - - // update BAR1 - bar1.setName("BAR1a"); - barService.update(bar1); - - // insert BAR2 - Bar bar2 = new Bar("BAR2"); - barService.create(bar2); - - // update BAR1 - bar1.setName("BAR1b"); - barService.update(bar1); - - // get BAR1 and BAR2 from the DB and check the audit values - // detach instances from persistence context to make sure we fire db - em.detach(bar1); - em.detach(bar2); - bar1 = barService.findOne(bar1.getId()); - bar2 = barService.findOne(bar2.getId()); - - assertNotNull(bar1); - assertNotNull(bar2); - assertEquals(OPERATION.UPDATE, bar1.getOperation()); - assertEquals(OPERATION.INSERT, bar2.getOperation()); - assertTrue(bar1.getTimestamp() > bar2.getTimestamp()); - - barService.deleteById(bar1.getId()); - barService.deleteById(bar2.getId()); - - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java deleted file mode 100644 index 18227abd28..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baeldung.persistence.audit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.spring.config.PersistenceTestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringDataJPABarAuditIntegrationTest { - - private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - logger.info("setUpBeforeClass()"); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - logger.info("tearDownAfterClass()"); - } - - @Autowired - @Qualifier("barSpringDataJpaService") - private IBarService barService; - - @Autowired - private EntityManagerFactory entityManagerFactory; - - private EntityManager em; - - @Before - public void setUp() throws Exception { - logger.info("setUp()"); - em = entityManagerFactory.createEntityManager(); - } - - @After - public void tearDown() throws Exception { - logger.info("tearDown()"); - em.close(); - } - - @Test - @WithMockUser(username = "tutorialuser") - public final void whenBarsModified_thenBarsAudited() { - Bar bar = new Bar("BAR1"); - barService.create(bar); - assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); - assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); - bar.setName("BAR2"); - bar = barService.update(bar); - assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); - assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); - } -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java deleted file mode 100644 index da840dc027..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.baeldung.persistence.hibernate; - -import java.util.List; - -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.model.Bar; -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.google.common.collect.Lists; - -public class FooFixtures { - private SessionFactory sessionFactory; - - public FooFixtures(final SessionFactory sessionFactory) { - super(); - - this.sessionFactory = sessionFactory; - } - - // API - - public void createBars() { - Session session = null; - Transaction tx = null; - session = sessionFactory.openSession(); - tx = session.getTransaction(); - try { - tx.begin(); - for (int i = 156; i < 160; i++) { - final Bar bar = new Bar(); - bar.setName("Bar_" + i); - final Foo foo = new Foo("Foo_" + (i + 120)); - foo.setBar(bar); - session.save(foo); - final Foo foo2 = new Foo(null); - if (i % 2 == 0) - foo2.setName("LuckyFoo" + (i + 120)); - foo2.setBar(bar); - session.save(foo2); - bar.getFooSet().add(foo); - bar.getFooSet().add(foo2); - session.merge(bar); - } - tx.commit(); - session.flush(); - } catch (final HibernateException he) { - if (tx != null) - tx.rollback(); - System.out.println("Not able to open session"); - he.printStackTrace(); - } catch (final Exception e) { - e.printStackTrace(); - } finally { - if (session != null) - session.close(); - } - - } - - public void createFoos() { - Session session = null; - Transaction tx = null; - session = sessionFactory.openSession(); - tx = session.getTransaction(); - final List fooList = Lists.newArrayList(); - for (int i = 35; i < 46; i++) { - - final Foo foo = new Foo(); - foo.setName("Foo_" + (i + 120)); - final Bar bar = new Bar("bar_" + i); - bar.getFooSet().add(foo); - foo.setBar(bar); - fooList.add(foo); - - } - try { - tx.begin(); - for (final Foo foo : fooList) { - - session.save(foo.getBar()); - session.save(foo); - } - tx.commit(); - session.flush(); - } catch (final HibernateException he) { - if (tx != null) - tx.rollback(); - System.out.println("Not able to open session"); - he.printStackTrace(); - } catch (final Exception e) { - e.printStackTrace(); - } finally { - if (session != null) - session.close(); - } - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java deleted file mode 100644 index fd7bc4aabf..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.baeldung.persistence.hibernate; - -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 org.hibernate.Criteria; -import org.hibernate.Query; -import org.hibernate.ScrollMode; -import org.hibernate.ScrollableResults; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.criterion.Projections; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.service.IFooService; -import com.baeldung.spring.config.PersistenceTestConfig; -import com.google.common.collect.Lists; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooPaginationPersistenceIntegrationTest { - - @Autowired - private IFooService fooService; - - @Autowired - private SessionFactory sessionFactory; - - private Session session; - - // tests - - @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))); - } - } - - session = sessionFactory.openSession(); - } - - @After - public final void after() { - session.close(); - } - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @SuppressWarnings("unchecked") - @Test - public final void whenRetrievingPaginatedEntities_thenCorrectSize() { - final int pageNumber = 1; - final int pageSize = 10; - - final Query query = session.createQuery("From Foo"); - query.setFirstResult((pageNumber - 1) * pageSize); - query.setMaxResults(pageSize); - final List fooList = query.list(); - - assertThat(fooList, hasSize(pageSize)); - } - - @SuppressWarnings("unchecked") - @Test - public final void whenRetrievingAllPages_thenCorrect() { - int pageNumber = 1; - final int pageSize = 10; - - final String countQ = "Select count (f.id) from Foo f"; - final Query countQuery = session.createQuery(countQ); - final Long countResult = (Long) countQuery.uniqueResult(); - - final List fooList = Lists.newArrayList(); - int totalEntities = 0; - final Query query = session.createQuery("From Foo"); - while (totalEntities < countResult) { - query.setFirstResult((pageNumber - 1) * pageSize); - query.setMaxResults(pageSize); - fooList.addAll(query.list()); - totalEntities = fooList.size(); - pageNumber++; - } - } - - @SuppressWarnings("unchecked") - @Test - public final void whenRetrievingLastPage_thenCorrectSize() { - final int pageSize = 10; - - final String countQ = "Select count (f.id) from Foo f"; - final Query countQuery = session.createQuery(countQ); - final Long countResults = (Long) countQuery.uniqueResult(); - final int lastPageNumber = (int) (Math.ceil(countResults / pageSize)); - - final Query selectQuery = session.createQuery("From Foo"); - selectQuery.setFirstResult((lastPageNumber - 1) * pageSize); - selectQuery.setMaxResults(pageSize); - final List lastPage = selectQuery.list(); - - assertThat(lastPage, hasSize(lessThan(pageSize + 1))); - } - - // testing - scrollable - - @Test - public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() { - final int pageSize = 10; - final String hql = "FROM Foo f order by f.name"; - final Query query = session.createQuery(hql); - - final ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY); - - // resultScroll.last(); - // final int totalResults = resultScroll.getRowNumber() + 1; - - resultScroll.first(); - resultScroll.scroll(0); - final List fooPage = Lists.newArrayList(); - int i = 0; - while (pageSize > i++) { - fooPage.add((Foo) resultScroll.get(0)); - if (!resultScroll.next()) { - break; - } - } - - assertThat(fooPage, hasSize(lessThan(10 + 1))); - } - - @SuppressWarnings("unchecked") - @Test - public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() { - final int pageSize = 10; - - final Criteria criteria = session.createCriteria(Foo.class); - criteria.setFirstResult(0); - criteria.setMaxResults(pageSize); - final List firstPage = criteria.list(); - - assertThat(firstPage, hasSize(pageSize)); - } - - @SuppressWarnings("unchecked") - @Test - public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() { - final Criteria criteriaCount = session.createCriteria(Foo.class); - criteriaCount.setProjection(Projections.rowCount()); - final Long count = (Long) criteriaCount.uniqueResult(); - - int pageNumber = 1; - final int pageSize = 10; - final List fooList = Lists.newArrayList(); - - final Criteria criteria = session.createCriteria(Foo.class); - int totalEntities = 0; - while (totalEntities < count.intValue()) { - criteria.setFirstResult((pageNumber - 1) * pageSize); - criteria.setMaxResults(pageSize); - fooList.addAll(criteria.list()); - totalEntities = fooList.size(); - pageNumber++; - } - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java deleted file mode 100644 index 8173088af0..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.baeldung.persistence.hibernate; - -import static org.junit.Assert.assertNull; - -import java.util.List; -import java.util.Set; - -import org.hibernate.Criteria; -import org.hibernate.NullPrecedence; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.criterion.Order; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Foo; -import com.baeldung.spring.config.PersistenceTestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -@SuppressWarnings("unchecked") -public class FooSortingPersistenceIntegrationTest { - - @Autowired - private SessionFactory sessionFactory; - - private Session session; - - @Before - public void before() { - session = sessionFactory.openSession(); - - session.beginTransaction(); - - final FooFixtures fooData = new FooFixtures(sessionFactory); - fooData.createBars(); - } - - @After - public void after() { - session.getTransaction().commit(); - session.close(); - } - - @Test - public final void whenHQlSortingByOneAttribute_thenPrintSortedResults() { - final String hql = "FROM Foo f ORDER BY f.name"; - final Query query = session.createQuery(hql); - final List fooList = query.list(); - for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); - } - } - - @Test - public final void whenHQlSortingByStringNullLast_thenLastNull() { - final String hql = "FROM Foo f ORDER BY f.name NULLS LAST"; - final Query query = session.createQuery(hql); - final List fooList = query.list(); - - assertNull(fooList.get(fooList.toArray().length - 1).getName()); - for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); - } - } - - @Test - public final void whenSortingByStringNullsFirst_thenReturnNullsFirst() { - final String hql = "FROM Foo f ORDER BY f.name NULLS FIRST"; - final Query query = session.createQuery(hql); - final List fooList = query.list(); - assertNull(fooList.get(0).getName()); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); - - } - } - - @Test - public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() { - final String hql = "FROM Foo f ORDER BY f.name ASC"; - final Query query = session.createQuery(hql); - final List fooList = query.list(); - for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); - } - } - - @Test - public final void whenHQlSortingByMultipleAttributes_thenSortedResults() { - final String hql = "FROM Foo f ORDER BY f.name, f.id"; - final Query query = session.createQuery(hql); - final List fooList = query.list(); - for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); - } - } - - @Test - public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() { - final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC"; - final Query query = session.createQuery(hql); - final List fooList = query.list(); - for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); - } - } - - @Test - public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("id")); - final List fooList = criteria.list(); - for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); - } - } - - @Test - public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("name")); - criteria.addOrder(Order.asc("id")); - final List fooList = criteria.list(); - for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); - } - } - - @Test - public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); - final List fooList = criteria.list(); - assertNull(fooList.get(fooList.toArray().length - 1).getName()); - for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); - } - } - - @Test - public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { - final Criteria criteria = session.createCriteria(Foo.class, "FOO"); - criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); - final List fooList = criteria.list(); - assertNull(fooList.get(0).getName()); - for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); - } - } - - @Test - public final void whenSortingBars_thenBarsWithSortedFoos() { - final String hql = "FROM Bar b ORDER BY b.id"; - final Query query = session.createQuery(hql); - final List barList = query.list(); - for (final Bar bar : barList) { - final Set fooSet = bar.getFooSet(); - System.out.println("Bar Id:" + bar.getId()); - for (final Foo foo : fooSet) { - System.out.println("FooName:" + foo.getName()); - } - } - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java deleted file mode 100644 index ef83af3a0d..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java +++ /dev/null @@ -1,262 +0,0 @@ -package com.baeldung.persistence.save; - -import com.baeldung.persistence.model.Person; -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.service.ServiceRegistry; -import org.junit.*; - -import static org.junit.Assert.*; - -/** - * Testing specific implementation details for different methods: - * persist, save, merge, update, saveOrUpdate. - */ -public class SaveMethodsIntegrationTest { - - private static SessionFactory sessionFactory; - - private Session session; - - @BeforeClass - public static void beforeTests() { - Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - } - - @Test - public void whenPersistTransient_thenSavedToDatabaseOnCommit() { - - Person person = new Person(); - person.setName("John"); - session.persist(person); - - session.getTransaction().commit(); - session.close(); - - session = sessionFactory.openSession(); - session.beginTransaction(); - - assertNotNull(session.get(Person.class, person.getId())); - - } - - @Test - public void whenPersistPersistent_thenNothingHappens() { - - Person person = new Person(); - person.setName("John"); - - session.persist(person); - Long id1 = person.getId(); - - session.persist(person); - Long id2 = person.getId(); - - assertEquals(id1, id2); - } - - @Test(expected = HibernateException.class) - public void whenPersistDetached_thenThrowsException() { - - Person person = new Person(); - person.setName("John"); - session.persist(person); - session.evict(person); - - session.persist(person); - - } - - @Test - public void whenSaveTransient_thenIdGeneratedImmediately() { - - Person person = new Person(); - person.setName("John"); - - assertNull(person.getId()); - - Long id = (Long) session.save(person); - - assertNotNull(id); - - session.getTransaction().commit(); - session.close(); - - assertEquals(id, person.getId()); - - session = sessionFactory.openSession(); - session.beginTransaction(); - - assertNotNull(session.get(Person.class, person.getId())); - - } - - @Test - public void whenSavePersistent_thenNothingHappens() { - - Person person = new Person(); - person.setName("John"); - Long id1 = (Long) session.save(person); - Long id2 = (Long) session.save(person); - assertEquals(id1, id2); - - } - - @Test - public void whenSaveDetached_thenNewInstancePersisted() { - - Person person = new Person(); - person.setName("John"); - Long id1 = (Long) session.save(person); - session.evict(person); - - Long id2 = (Long) session.save(person); - assertNotEquals(id1, id2); - - } - - @Test - public void whenMergeDetached_thenEntityUpdatedFromDatabase() { - - Person person = new Person(); - person.setName("John"); - session.save(person); - session.evict(person); - - person.setName("Mary"); - Person mergedPerson = (Person) session.merge(person); - - assertNotSame(person, mergedPerson); - assertEquals("Mary", mergedPerson.getName()); - - } - - @Test - public void whenMergeTransient_thenNewEntitySavedToDatabase() { - - Person person = new Person(); - person.setName("John"); - Person mergedPerson = (Person) session.merge(person); - - session.getTransaction().commit(); - session.beginTransaction(); - - assertNull(person.getId()); - assertNotNull(mergedPerson.getId()); - - } - - @Test - public void whenMergePersistent_thenReturnsSameObject() { - - Person person = new Person(); - person.setName("John"); - session.save(person); - - Person mergedPerson = (Person) session.merge(person); - - assertSame(person, mergedPerson); - - } - - @Test - public void whenUpdateDetached_thenEntityUpdatedFromDatabase() { - - Person person = new Person(); - person.setName("John"); - session.save(person); - session.evict(person); - - person.setName("Mary"); - session.update(person); - assertEquals("Mary", person.getName()); - - } - - @Test(expected = HibernateException.class) - public void whenUpdateTransient_thenThrowsException() { - - Person person = new Person(); - person.setName("John"); - session.update(person); - - } - - @Test - public void whenUpdatePersistent_thenNothingHappens() { - - Person person = new Person(); - person.setName("John"); - session.save(person); - - session.update(person); - - } - - @Test - public void whenSaveOrUpdateDetached_thenEntityUpdatedFromDatabase() { - - Person person = new Person(); - person.setName("John"); - session.save(person); - session.evict(person); - - person.setName("Mary"); - session.saveOrUpdate(person); - assertEquals("Mary", person.getName()); - - } - - @Test - public void whenSaveOrUpdateTransient_thenSavedToDatabaseOnCommit() { - - Person person = new Person(); - person.setName("John"); - session.saveOrUpdate(person); - - session.getTransaction().commit(); - session.close(); - - session = sessionFactory.openSession(); - session.beginTransaction(); - - assertNotNull(session.get(Person.class, person.getId())); - - } - - @Test - public void whenSaveOrUpdatePersistent_thenNothingHappens() { - - Person person = new Person(); - person.setName("John"); - session.save(person); - - session.saveOrUpdate(person); - - } - - @After - public void tearDown() { - session.getTransaction().commit(); - session.close(); - } - - @AfterClass - public static void afterTests() { - sessionFactory.close(); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java deleted file mode 100644 index 146f8e9622..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Foo; -import com.baeldung.spring.config.PersistenceTestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooServiceBasicPersistenceIntegrationTest { - - @Autowired - private SessionFactory sessionFactory; - - @Autowired - private IFooService fooService; - - private Session session; - - // tests - - @Before - public final void before() { - session = sessionFactory.openSession(); - } - - @After - public final void after() { - session.close(); - } - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - fooService.create(new Foo(randomAlphabetic(6))); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index 6d426849a6..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -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.model.Foo; -import com.baeldung.spring.config.PersistenceTestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooServicePersistenceIntegrationTest { - - @Autowired - @Qualifier("fooHibernateService") - 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) - @Ignore("work in progress") - public final void whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo()); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenEntityWithLongNameIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - @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); - } - - @Test(expected = DataAccessException.class) - public final void temp_whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java deleted file mode 100644 index d9353f1ad1..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.baeldung.persistence.service; - -import java.util.List; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertEquals; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.exception.SQLGrammarException; -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; - -import com.baeldung.persistence.model.Foo; -import com.baeldung.spring.PersistenceConfig; - -@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 IFooService fooService; - - private Session session; - - @Before - public final void before() { - session = sessionFactory.openSession(); - Assume.assumeTrue(getAllFoosExists()); - Assume.assumeTrue(getFoosByNameExists()); - } - - private boolean getFoosByNameExists() { - try { - Query 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 { - Query 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 - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - @SuppressWarnings("unchecked") - 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 - Query namedQuery = session.getNamedQuery("callGetAllFoos"); - @SuppressWarnings("unchecked") - 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() - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); - @SuppressWarnings("unchecked") - List allFoosByName = sqlQuery.list(); - for (Foo foo : allFoosByName) { - LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); - } - - // Stored procedure getFoosByName using getNamedQuery() - Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); - @SuppressWarnings("unchecked") - List allFoosByName2 = namedQuery.list(); - for (Foo foo : allFoosByName2) { - LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); - } - - } -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java deleted file mode 100644 index 5a73e39ca2..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.persistence.service; - -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.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Child; -import com.baeldung.persistence.model.Parent; -import com.baeldung.spring.config.PersistenceTestConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ParentServicePersistenceIntegrationTest { - - @Autowired - private IParentService service; - - @Autowired - private IChildService childService; - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @Test - public final void whenOneToOneEntitiesAreCreated_thenNoExceptions() { - final Child childEntity = new Child(); - childService.create(childEntity); - - final Parent parentEntity = new Parent(childEntity); - service.create(parentEntity); - - System.out.println("Child = " + childService.findOne(childEntity.getId())); - System.out.println("Child - parent = " + childService.findOne(childEntity.getId()).getParent()); - - System.out.println("Parent = " + service.findOne(parentEntity.getId())); - System.out.println("Parent - child = " + service.findOne(parentEntity.getId()).getChild()); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenChildIsDeletedWhileParentStillHasForeignKeyToIt_thenDataException() { - final Child childEntity = new Child(); - childService.create(childEntity); - - final Parent parentEntity = new Parent(childEntity); - service.create(parentEntity); - - childService.delete(childEntity); - } - - @Test - public final void whenChildIsDeletedAfterTheParent_thenNoExceptions() { - final Child childEntity = new Child(); - childService.create(childEntity); - - final Parent parentEntity = new Parent(childEntity); - service.create(parentEntity); - - service.delete(parentEntity); - childService.delete(childEntity); - } - -} diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java deleted file mode 100644 index 9bf55c902a..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.baeldung.spring.config; - -import java.util.Properties; - -import javax.sql.DataSource; - -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.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.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 com.baeldung.persistence.dao.IBarAuditableDao; -import com.baeldung.persistence.dao.IBarDao; -import com.baeldung.persistence.dao.IFooAuditableDao; -import com.baeldung.persistence.dao.IFooDao; -import com.baeldung.persistence.dao.impl.BarAuditableDao; -import com.baeldung.persistence.dao.impl.BarDao; -import com.baeldung.persistence.dao.impl.BarJpaDao; -import com.baeldung.persistence.dao.impl.FooAuditableDao; -import com.baeldung.persistence.dao.impl.FooDao; -import com.baeldung.persistence.service.IBarAuditableService; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.persistence.service.IFooAuditableService; -import com.baeldung.persistence.service.IFooService; -import com.baeldung.persistence.service.impl.BarAuditableService; -import com.baeldung.persistence.service.impl.BarJpaService; -import com.baeldung.persistence.service.impl.BarSpringDataJpaService; -import com.baeldung.persistence.service.impl.FooAuditableService; -import com.baeldung.persistence.service.impl.FooService; -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") -@EnableJpaAuditing -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.persistence" }) -public class PersistenceTestConfig { - - @Autowired - private Environment env; - - public PersistenceTestConfig() { - super(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory() { - final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); - emf.setDataSource(restDataSource()); - emf.setPackagesToScan(new String[] { "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 IBarService barJpaService() { - return new BarJpaService(); - } - - @Bean - public IBarService barSpringDataJpaService() { - return new BarSpringDataJpaService(); - } - - @Bean - public IFooService fooHibernateService() { - return new FooService(); - } - - @Bean - public IBarAuditableService barHibernateAuditableService() { - return new BarAuditableService(); - } - - @Bean - public IFooAuditableService fooHibernateAuditableService() { - return new FooAuditableService(); - } - - @Bean - public IBarDao barJpaDao() { - return new BarJpaDao(); - } - - @Bean - public IBarDao barHibernateDao() { - return new BarDao(); - } - - @Bean - public IBarAuditableDao barHibernateAuditableDao() { - return new BarAuditableDao(); - } - - @Bean - public IFooDao fooHibernateDao() { - return new FooDao(); - } - - @Bean - public IFooAuditableDao fooHibernateAuditableDao() { - return new FooAuditableDao(); - } - - private final 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"); - // hibernateProperties.setProperty("hibernate.format_sql", "true"); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "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-hibernate4/src/test/resources/.gitignore b/persistence-modules/spring-hibernate4/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/persistence-modules/spring-hibernate4/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 diff --git a/persistence-modules/spring-hibernate4/src/test/resources/fetching.cfg.xml b/persistence-modules/spring-hibernate4/src/test/resources/fetching.cfg.xml deleted file mode 100644 index 55a3aeb51c..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/resources/fetching.cfg.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - org.h2.Driver - jdbc:h2:mem:testdb - sa - - org.hibernate.dialect.H2Dialect - update - true - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml b/persistence-modules/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml deleted file mode 100644 index 8fcf578660..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - org.h2.Driver - jdbc:h2:mem:testdb - sa - - org.hibernate.dialect.H2Dialect - update - true - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/src/test/resources/persistence-h2.properties b/persistence-modules/spring-hibernate4/src/test/resources/persistence-h2.properties deleted file mode 100644 index 911619193b..0000000000 --- a/persistence-modules/spring-hibernate4/src/test/resources/persistence-h2.properties +++ /dev/null @@ -1,13 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:test -jdbc.user=sa -jdbc.pass= - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop - -# envers.X -envers.audit_table_suffix=_audit_log From 0ba96c9c43465a133934b244313e7e36433233d9 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 28 Sep 2020 23:12:26 +0530 Subject: [PATCH 2/6] JAVA-2432: Moved 1 article to hibernate-enterprise --- .../hibernate-enterprise/README.md | 3 ++- .../hibernate-enterprise/pom.xml | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/persistence-modules/hibernate-enterprise/README.md b/persistence-modules/hibernate-enterprise/README.md index c5606d0970..1a86c32afa 100644 --- a/persistence-modules/hibernate-enterprise/README.md +++ b/persistence-modules/hibernate-enterprise/README.md @@ -9,4 +9,5 @@ This module contains articles about enterprise concerns such as Multitenancy, Er - [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) - [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) - [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) -- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) \ No newline at end of file +- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) +- [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml index ae58e409c4..c088cc1eca 100644 --- a/persistence-modules/hibernate-enterprise/pom.xml +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -61,13 +61,25 @@ ${byte-buddy.version} test + + org.hsqldb + hsqldb + ${hsqldb.version} + test + - geodb-repo - GeoDB repository - http://repo.boundlessgeo.com/main/ + osgeo + OSGeo Release Repository + https://repo.osgeo.org/repository/release/ + + false + + + true + @@ -77,6 +89,7 @@ 2.2.3 3.8.0 0.9 + 2.3.4 From d77c22b05f944119f7bde91af4b35deb9081f979 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 28 Sep 2020 23:13:14 +0530 Subject: [PATCH 3/6] JAVA-2432: Moved 1 article to hibernate-enterprise --- .../baeldung/persistence/model/Person.java | 31 ++ .../save/SaveMethodsIntegrationTest.java | 291 ++++++++++++++++++ 2 files changed, 322 insertions(+) create mode 100644 persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java create mode 100644 persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java new file mode 100644 index 0000000000..6a95a7acf5 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java @@ -0,0 +1,31 @@ +package com.baeldung.persistence.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private Long id; + + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java new file mode 100644 index 0000000000..8c571428b4 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java @@ -0,0 +1,291 @@ +package com.baeldung.persistence.save; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +import javax.persistence.PersistenceException; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.HSQLDialect; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.persistence.model.Person; + +/** + * Testing specific implementation details for different methods: + * persist, save, merge, update, saveOrUpdate. + */ +public class SaveMethodsIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + private boolean doNotCommit = false; + + @BeforeClass + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(Person.class) + .setProperty("hibernate.dialect", HSQLDialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") + .setProperty("hibernate.connection.username", "sa") + .setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + doNotCommit = false; + } + + @Test + public void whenPersistTransient_thenSavedToDatabaseOnCommit() { + + Person person = new Person(); + person.setName("John"); + session.persist(person); + + session.getTransaction() + .commit(); + session.close(); + + session = sessionFactory.openSession(); + session.beginTransaction(); + + assertNotNull(session.get(Person.class, person.getId())); + + } + + @Test + public void whenPersistPersistent_thenNothingHappens() { + + Person person = new Person(); + person.setName("John"); + + session.persist(person); + Long id1 = person.getId(); + + session.persist(person); + Long id2 = person.getId(); + + assertEquals(id1, id2); + } + + @Test(expected = PersistenceException.class) + public void whenPersistDetached_thenThrowsException() { + + doNotCommit = true; + + Person person = new Person(); + person.setName("John"); + session.persist(person); + session.evict(person); + + session.persist(person); + } + + @Test + public void whenMergeDetached_thenEntityUpdatedFromDatabase() { + + Person person = new Person(); + person.setName("John"); + session.save(person); + session.flush(); + session.evict(person); + + person.setName("Mary"); + Person mergedPerson = (Person) session.merge(person); + + assertNotSame(person, mergedPerson); + assertEquals("Mary", mergedPerson.getName()); + + } + + @Test + public void whenSaveTransient_thenIdGeneratedImmediately() { + + Person person = new Person(); + person.setName("John"); + + assertNull(person.getId()); + + Long id = (Long) session.save(person); + + assertNotNull(id); + + session.getTransaction() + .commit(); + session.close(); + + assertEquals(id, person.getId()); + + session = sessionFactory.openSession(); + session.beginTransaction(); + + assertNotNull(session.get(Person.class, person.getId())); + + } + + @Test + public void whenSavePersistent_thenNothingHappens() { + + Person person = new Person(); + person.setName("John"); + Long id1 = (Long) session.save(person); + Long id2 = (Long) session.save(person); + assertEquals(id1, id2); + + } + + @Test + public void whenSaveDetached_thenNewInstancePersisted() { + + Person person = new Person(); + person.setName("John"); + Long id1 = (Long) session.save(person); + session.evict(person); + + Long id2 = (Long) session.save(person); + assertNotEquals(id1, id2); + + } + + @Test + public void whenMergeTransient_thenNewEntitySavedToDatabase() { + + Person person = new Person(); + person.setName("John"); + Person mergedPerson = (Person) session.merge(person); + + session.getTransaction() + .commit(); + session.beginTransaction(); + + assertNull(person.getId()); + assertNotNull(mergedPerson.getId()); + + } + + @Test + public void whenMergePersistent_thenReturnsSameObject() { + + Person person = new Person(); + person.setName("John"); + session.save(person); + + Person mergedPerson = (Person) session.merge(person); + + assertSame(person, mergedPerson); + + } + + @Test + public void whenUpdateDetached_thenEntityUpdatedFromDatabase() { + + Person person = new Person(); + person.setName("John"); + session.save(person); + session.evict(person); + + person.setName("Mary"); + session.update(person); + assertEquals("Mary", person.getName()); + + } + + @Test(expected = HibernateException.class) + public void whenUpdateTransient_thenThrowsException() { + + Person person = new Person(); + person.setName("John"); + session.update(person); + + } + + @Test + public void whenUpdatePersistent_thenNothingHappens() { + + Person person = new Person(); + person.setName("John"); + session.save(person); + + session.update(person); + + } + + @Test + public void whenSaveOrUpdateDetached_thenEntityUpdatedFromDatabase() { + + Person person = new Person(); + person.setName("John"); + session.save(person); + session.evict(person); + + person.setName("Mary"); + session.saveOrUpdate(person); + assertEquals("Mary", person.getName()); + + } + + @Test + public void whenSaveOrUpdateTransient_thenSavedToDatabaseOnCommit() { + + Person person = new Person(); + person.setName("John"); + session.saveOrUpdate(person); + + session.getTransaction() + .commit(); + session.close(); + + session = sessionFactory.openSession(); + session.beginTransaction(); + + assertNotNull(session.get(Person.class, person.getId())); + + } + + @Test + public void whenSaveOrUpdatePersistent_thenNothingHappens() { + + Person person = new Person(); + person.setName("John"); + session.save(person); + + session.saveOrUpdate(person); + + } + + @After + public void tearDown() { + if (!doNotCommit) { + session.getTransaction() + .commit(); + } + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} From 7de65d1211d54e5b15fdd6ee4c432e04b1c74e2a Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 28 Sep 2020 23:13:49 +0530 Subject: [PATCH 4/6] JAVA-2432: removed unused module from parent pom --- persistence-modules/pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index def2deb941..0e9c04f55d 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -80,8 +80,7 @@ spring-data-redis spring-data-solr spring-hibernate-3 - spring-hibernate-5 - spring-hibernate4 + spring-hibernate-5 spring-jpa spring-jpa-2 spring-jdbc From 2dd77a259db8eaa15f1a61b2752fee17d85611d4 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 28 Sep 2020 23:17:31 +0530 Subject: [PATCH 5/6] JAVA-2432: Moved 5 articles to spring-data-jpa-query-2 --- .../spring-data-jpa-query-2/README.md | 6 + .../spring-data-jpa-query-2/pom.xml | 58 +++++ .../baeldung/config/PersistenceConfig.java | 186 ++++++++++++++ .../baeldung/config/PersistenceXmlConfig.java | 18 ++ .../hibernate/audit/AuditorAwareImpl.java | 18 ++ .../hibernate/fetching/model/OrderDetail.java | 58 +++++ .../hibernate/fetching/model/UserEager.java | 71 +++++ .../hibernate/fetching/model/UserLazy.java | 71 +++++ .../fetching/util/HibernateUtil.java | 29 +++ .../fetching/view/FetchingAppView.java | 68 +++++ .../persistence/dao/BookRepository.java | 9 - .../persistence/dao/BookRepositoryCustom.java | 11 - .../persistence/dao/BookRepositoryImpl.java | 44 ---- .../baeldung/persistence/dao/BookService.java | 25 -- .../persistence/dao/BookSpecifications.java | 16 -- .../persistence/dao/IBarAuditableDao.java | 8 + .../persistence/dao/IBarCrudRepository.java | 10 + .../com/baeldung/persistence/dao/IBarDao.java | 8 + .../baeldung/persistence/dao/IChildDao.java | 8 + .../persistence/dao/IFooAuditableDao.java | 8 + .../com/baeldung/persistence/dao/IFooDao.java | 8 + .../baeldung/persistence/dao/IParentDao.java | 8 + .../persistence/dao/common/AbstractDao.java | 14 + .../common/AbstractHibernateAuditableDao.java | 37 +++ .../dao/common/AbstractHibernateDao.java | 59 +++++ .../dao/common/AbstractJpaDao.java | 56 ++++ .../dao/common/GenericHibernateDao.java | 13 + .../dao/common/IAuditOperations.java | 14 + .../persistence/dao/common/IGenericDao.java | 7 + .../persistence/dao/common/IOperations.java | 20 ++ .../persistence/dao/impl/BarAuditableDao.java | 28 ++ .../baeldung/persistence/dao/impl/BarDao.java | 19 ++ .../persistence/dao/impl/BarJpaDao.java | 19 ++ .../persistence/dao/impl/ChildDao.java | 19 ++ .../persistence/dao/impl/FooAuditableDao.java | 17 ++ .../baeldung/persistence/dao/impl/FooDao.java | 19 ++ .../persistence/dao/impl/ParentDao.java | 19 ++ .../com/baeldung/persistence/model/Bar.java | 242 ++++++++++++++++++ .../com/baeldung/persistence/model/Book.java | 36 --- .../com/baeldung/persistence/model/Child.java | 51 ++++ .../com/baeldung/persistence/model/Foo.java | 105 ++++++++ .../baeldung/persistence/model/Parent.java | 60 +++++ .../baeldung/persistence/model/Person.java | 31 +++ .../service/IBarAuditableService.java | 8 + .../persistence/service/IBarService.java | 8 + .../persistence/service/IChildService.java | 8 + .../service/IFooAuditableService.java | 8 + .../persistence/service/IFooService.java | 8 + .../persistence/service/IParentService.java | 8 + .../AbstractHibernateAuditableService.java | 30 +++ .../common/AbstractHibernateService.java | 42 +++ .../service/common/AbstractJpaService.java | 42 +++ .../service/common/AbstractService.java | 42 +++ .../common/AbstractSpringDataJpaService.java | 48 ++++ .../service/impl/BarAuditableService.java | 41 +++ .../service/impl/BarJpaService.java | 30 +++ .../persistence/service/impl/BarService.java | 30 +++ .../service/impl/BarSpringDataJpaService.java | 26 ++ .../service/impl/ChildService.java | 28 ++ .../service/impl/FooAuditableService.java | 41 +++ .../persistence/service/impl/FooService.java | 30 +++ .../service/impl/ParentService.java | 28 ++ .../src/main/resources/fetching.cfg.xml | 20 ++ .../src/main/resources/fetchingLazy.cfg.xml | 17 ++ .../resources/fetching_create_queries.sql | 14 + .../src/main/resources/hibernate5Config.xml | 34 +++ .../resources/hibernate5Configuration.xml | 30 +++ .../src/main/resources/immutable.cfg.xml | 38 +++ .../src/main/resources/insert_statements.sql | 31 +++ .../src/main/resources/logback.xml | 19 ++ .../resources/persistence-mysql.properties | 13 + .../src/main/resources/stored_procedure.sql | 20 ++ .../src/main/resources/webSecurityConfig.xml | 37 +++ .../HibernateFetchingIntegrationTest.java | 42 +++ .../persistence/IntegrationTestSuite.java | 25 ++ .../persistence/audit/AuditTestSuite.java | 14 + .../EnversFooBarAuditIntegrationTest.java | 146 +++++++++++ .../audit/JPABarAuditIntegrationTest.java | 104 ++++++++ .../SpringDataJPABarAuditIntegrationTest.java | 78 ++++++ .../persistence/hibernate/FooFixtures.java | 101 ++++++++ ...oPaginationPersistenceIntegrationTest.java | 185 +++++++++++++ .../FooSortingPersistenceIntegrationTest.java | 174 +++++++++++++ ...erviceBasicPersistenceIntegrationTest.java | 55 ++++ .../FooServicePersistenceIntegrationTest.java | 64 +++++ .../service/FooStoredProceduresLiveTest.java | 121 +++++++++ ...rentServicePersistenceIntegrationTest.java | 70 +++++ .../spring/config/PersistenceTestConfig.java | 179 +++++++++++++ .../ArticleRepositoryIntegrationTest.java | 3 + .../src/test/resources/fetching.cfg.xml | 19 ++ .../src/test/resources/fetchingLazy.cfg.xml | 19 ++ .../test/resources/persistence-h2.properties | 13 + 91 files changed, 3681 insertions(+), 141 deletions(-) create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceConfig.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceXmlConfig.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java delete mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepository.java delete mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryCustom.java delete mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookService.java delete mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookSpecifications.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IChildDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IParentDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IOperations.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java delete mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Book.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Person.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IChildService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IParentService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ChildService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ParentService.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching.cfg.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/fetchingLazy.cfg.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching_create_queries.sql create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Config.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Configuration.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/immutable.cfg.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/insert_statements.sql create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/logback.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/persistence-mysql.properties create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/stored_procedure.sql create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/resources/webSecurityConfig.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml create mode 100644 persistence-modules/spring-data-jpa-query-2/src/test/resources/persistence-h2.properties diff --git a/persistence-modules/spring-data-jpa-query-2/README.md b/persistence-modules/spring-data-jpa-query-2/README.md index fdb4ce3db7..bdc8d7cb32 100644 --- a/persistence-modules/spring-data-jpa-query-2/README.md +++ b/persistence-modules/spring-data-jpa-query-2/README.md @@ -6,6 +6,12 @@ This module contains articles about querying data using Spring Data JPA - [Spring Data JPA @Query Annotation](https://www.baeldung.com/spring-data-jpa-query) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) +- [Hibernate Pagination](https://www.baeldung.com/hibernate-pagination) +- [Sorting with Hibernate](https://www.baeldung.com/hibernate-sort) +- [Stored Procedures with Hibernate](https://www.baeldung.com/stored-procedures-with-hibernate-tutorial) +- [Eager/Lazy Loading In Hibernate](https://www.baeldung.com/hibernate-lazy-eager-loading) +- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) + - More articles: [[<-- prev]](../spring-data-jpa-query) ### Eclipse Config diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index 231640284e..abac7b28da 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -18,6 +18,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.security + spring-security-core + com.h2database @@ -28,6 +32,55 @@ com.fasterxml.jackson.core jackson-databind + + + org.hibernate + hibernate-envers + + + javax.transaction + jta + ${jta.version} + + + mysql + mysql-connector-java + + + com.google.guava + guava + ${guava.version} + + + org.apache.tomcat + tomcat-dbcp + ${tomcat-dbcp.version} + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.hibernate + hibernate-envers + ${hibernate.version} + + + org.springframework + spring-test + test + + + org.springframework.security + spring-security-test + test + + + org.hsqldb + hsqldb + test + @@ -35,5 +88,10 @@ 2.22.2 5.6.2 4.13 + 9.0.0.M26 + 1.1 + 21.0 + + 5.2.10.Final \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceConfig.java new file mode 100644 index 0000000000..a0d70ed006 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceConfig.java @@ -0,0 +1,186 @@ +package com.baeldung.config; + +import java.util.Properties; + +import javax.sql.DataSource; + +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.domain.AuditorAware; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +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 com.baeldung.hibernate.audit.AuditorAwareImpl; +import com.baeldung.persistence.dao.IBarAuditableDao; +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.dao.IFooAuditableDao; +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.dao.impl.BarAuditableDao; +import com.baeldung.persistence.dao.impl.BarDao; +import com.baeldung.persistence.dao.impl.BarJpaDao; +import com.baeldung.persistence.dao.impl.FooAuditableDao; +import com.baeldung.persistence.dao.impl.FooDao; +import com.baeldung.persistence.service.IBarAuditableService; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.persistence.service.IFooAuditableService; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.persistence.service.impl.BarAuditableService; +import com.baeldung.persistence.service.impl.BarJpaService; +import com.baeldung.persistence.service.impl.BarSpringDataJpaService; +import com.baeldung.persistence.service.impl.FooAuditableService; +import com.baeldung.persistence.service.impl.FooService; +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager", entityManagerFactoryRef = "jpaEntityManager") +@EnableJpaAuditing(auditorAwareRef = "auditorProvider") +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "com.baeldung.persistence" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + @Bean("auditorProvider") + public AuditorAware auditorProvider() { + return new AuditorAwareImpl(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean("jpaEntityManager") + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(restDataSource()); + emf.setPackagesToScan(new String[] { "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 IBarService barJpaService() { + return new BarJpaService(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooHibernateService() { + return new FooService(); + } + + @Bean + public IBarAuditableService barHibernateAuditableService() { + return new BarAuditableService(); + } + + @Bean + public IFooAuditableService fooHibernateAuditableService() { + return new FooAuditableService(); + } + + @Bean + public IBarDao barJpaDao() { + return new BarJpaDao(); + } + + @Bean + public IBarDao barHibernateDao() { + return new BarDao(); + } + + @Bean + public IBarAuditableDao barHibernateAuditableDao() { + return new BarAuditableDao(); + } + + @Bean + public IFooDao fooHibernateDao() { + return new FooDao(); + } + + @Bean + public IFooAuditableDao fooHibernateAuditableDao() { + return new FooAuditableDao(); + } + + private final 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"); + // hibernateProperties.setProperty("hibernate.format_sql", "true"); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "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-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceXmlConfig.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceXmlConfig.java new file mode 100644 index 0000000000..388494b21a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/config/PersistenceXmlConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@ComponentScan({ "com.baeldung.persistence.dao", "com.baeldung.persistence.service" }) +@ImportResource({ "classpath:hibernate4Config.xml" }) +public class PersistenceXmlConfig { + + public PersistenceXmlConfig() { + super(); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java new file mode 100644 index 0000000000..5dd12e6841 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java @@ -0,0 +1,18 @@ +package com.baeldung.hibernate.audit; + +import java.util.Optional; + +import org.springframework.data.domain.AuditorAware; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class AuditorAwareImpl implements AuditorAware { + + @Override + public Optional getCurrentAuditor() { + return Optional.ofNullable(SecurityContextHolder.getContext()) + .map(e -> e.getAuthentication()) + .map(Authentication::getName); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java new file mode 100644 index 0000000000..f4a9b8a678 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; + +@Entity +@Table(name = "USER_ORDER") +public class OrderDetail implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name = "ORDER_ID") + private Long orderId; + + public OrderDetail() { + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.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; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java new file mode 100644 index 0000000000..9fda4c43bb --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table(name = "USER") +public class UserEager implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.EAGER) + private Set orderDetail = new HashSet(); + + public UserEager() { + } + + public UserEager(final Long userId) { + super(); + this.userId = userId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.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 UserEager other = (UserEager) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java new file mode 100644 index 0000000000..a78eaa4ac0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.fetching.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table(name = "USER") +public class UserLazy implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; + + @OneToMany(fetch = FetchType.LAZY) + private Set orderDetail = new HashSet(); + + public UserLazy() { + } + + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.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 UserLazy other = (UserLazy) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java new file mode 100644 index 0000000000..c7be96abb7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.fetching.util; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateUtil { + + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + // two config files are there + // one with lazy loading enabled + // another lazy = false + SessionFactory sf; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + return sf.openSession(); + } + + public static Session getHibernateSession() { + return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession(); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java new file mode 100644 index 0000000000..35cdd254e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -0,0 +1,68 @@ +package com.baeldung.hibernate.fetching.view; + +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.model.UserEager; +import com.baeldung.hibernate.fetching.model.UserLazy; +import com.baeldung.hibernate.fetching.util.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.Transaction; + +import java.util.List; +import java.util.Set; + +public class FetchingAppView { + + public FetchingAppView() { + + } + + // lazily loaded + public Set lazyLoaded() { + final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); + List users = sessionLazy.createQuery("From UserLazy").list(); + UserLazy userLazyLoaded = users.get(0); + // since data is lazyloaded so data won't be initialized + return (userLazyLoaded.getOrderDetail()); + } + + // eagerly loaded + public Set eagerLoaded() { + final Session sessionEager = HibernateUtil.getHibernateSession(); + // data should be loaded in the following line + // also note the queries generated + List user = sessionEager.createQuery("From UserEager").list(); + UserEager userEagerLoaded = user.get(0); + return userEagerLoaded.getOrderDetail(); + } + + // creates test data + // call this method to create the data in the database + public void createTestData() { + + final Session session = HibernateUtil.getHibernateSession("lazy"); + Transaction tx = session.beginTransaction(); + final UserLazy user1 = new UserLazy(); + final UserLazy user2 = new UserLazy(); + final UserLazy user3 = new UserLazy(); + + session.save(user1); + session.save(user2); + session.save(user3); + + final OrderDetail order1 = new OrderDetail(); + final OrderDetail order2 = new OrderDetail(); + final OrderDetail order3 = new OrderDetail(); + final OrderDetail order4 = new OrderDetail(); + final OrderDetail order5 = new OrderDetail(); + + session.saveOrUpdate(order1); + session.saveOrUpdate(order2); + session.saveOrUpdate(order3); + session.saveOrUpdate(order4); + session.saveOrUpdate(order5); + + tx.commit(); + session.close(); + + } +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepository.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepository.java deleted file mode 100644 index 48620f4ff1..0000000000 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Book; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -public interface BookRepository extends JpaRepository, BookRepositoryCustom, JpaSpecificationExecutor { - -} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryCustom.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryCustom.java deleted file mode 100644 index eda34542df..0000000000 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryCustom.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Book; - -import java.util.List; - -public interface BookRepositoryCustom { - - List findBooksByAuthorNameAndTitle(String authorName, String title); - -} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryImpl.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryImpl.java deleted file mode 100644 index 7f5bedd018..0000000000 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookRepositoryImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Book; -import org.springframework.stereotype.Repository; - -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import java.util.ArrayList; -import java.util.List; - -@Repository -public class BookRepositoryImpl implements BookRepositoryCustom { - - private EntityManager em; - - public BookRepositoryImpl(EntityManager em) { - this.em = em; - } - - @Override - public List findBooksByAuthorNameAndTitle(String authorName, String title) { - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(Book.class); - - Root book = cq.from(Book.class); - List predicates = new ArrayList<>(); - - if (authorName != null) { - predicates.add(cb.equal(book.get("author"), authorName)); - } - if (title != null) { - predicates.add(cb.like(book.get("title"), "%" + title + "%")); - } - cq.where(predicates.toArray(new Predicate[0])); - - TypedQuery query = em.createQuery(cq); - return query.getResultList(); - } - -} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookService.java deleted file mode 100644 index 4165cd8eb9..0000000000 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Book; -import org.springframework.stereotype.Service; - -import java.util.List; - -import static com.baeldung.persistence.dao.BookSpecifications.hasAuthor; -import static com.baeldung.persistence.dao.BookSpecifications.titleContains; -import static org.springframework.data.jpa.domain.Specification.where; - -@Service -public class BookService { - - private BookRepository bookRepository; - - public BookService(BookRepository bookRepository) { - this.bookRepository = bookRepository; - } - - public List query(String author, String title) { - return bookRepository.findAll(where(hasAuthor(author)).and(titleContains(title))); - } - -} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookSpecifications.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookSpecifications.java deleted file mode 100644 index 16646a5b4b..0000000000 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/BookSpecifications.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.persistence.dao; - -import com.baeldung.persistence.model.Book; -import org.springframework.data.jpa.domain.Specification; - -public class BookSpecifications { - - public static Specification hasAuthor(String author) { - return (book, cq, cb) -> cb.equal(book.get("author"), author); - } - - public static Specification titleContains(String title) { - return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%"); - } - -} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java new file mode 100644 index 0000000000..182b493592 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarAuditableDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.dao.common.IAuditOperations; +import com.baeldung.persistence.model.Bar; + +public interface IBarAuditableDao extends IBarDao, IAuditOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java new file mode 100644 index 0000000000..4d7db64240 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarCrudRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.persistence.dao; + +import java.io.Serializable; + +import com.baeldung.persistence.model.Bar; +import org.springframework.data.repository.CrudRepository; + +public interface IBarCrudRepository extends CrudRepository { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarDao.java new file mode 100644 index 0000000000..7896a2a84a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IBarDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.model.Bar; + +public interface IBarDao extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IChildDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IChildDao.java new file mode 100644 index 0000000000..a55a0b0598 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IChildDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IChildDao extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java new file mode 100644 index 0000000000..ddbb685988 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooAuditableDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.dao.common.IAuditOperations; +import com.baeldung.persistence.model.Foo; + +public interface IFooAuditableDao extends IFooDao, IAuditOperations { + // +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooDao.java new file mode 100644 index 0000000000..0935772dbd --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IFooDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IFooDao extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IParentDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IParentDao.java new file mode 100644 index 0000000000..03680158bb --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/IParentDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.dao; + +import com.baeldung.persistence.model.Parent; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IParentDao extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java new file mode 100644 index 0000000000..5a6c76a93a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java @@ -0,0 +1,14 @@ +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-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java new file mode 100644 index 0000000000..41184669ad --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java @@ -0,0 +1,37 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.envers.AuditReader; +import org.hibernate.envers.AuditReaderFactory; +import org.hibernate.envers.query.AuditQuery; + +@SuppressWarnings("unchecked") +public class AbstractHibernateAuditableDao extends AbstractHibernateDao implements IAuditOperations { + + @Override + public List getEntitiesAtRevision(final Number revision) { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forEntitiesAtRevision(clazz, revision); + final List resultList = query.getResultList(); + return resultList; + } + + @Override + public List getEntitiesModifiedAtRevision(final Number revision) { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forEntitiesModifiedAtRevision(clazz, revision); + final List resultList = query.getResultList(); + return resultList; + } + + @Override + public List getRevisions() { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forRevisionsOfEntity(clazz, true, true); + final List resultList = query.getResultList(); + return resultList; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java new file mode 100644 index 0000000000..f3ade67f80 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java @@ -0,0 +1,59 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Preconditions; + +@SuppressWarnings("unchecked") +public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { + + @Autowired + protected SessionFactory sessionFactory; + + // API + + @Override + 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 void create(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().saveOrUpdate(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); + delete(entity); + } + + protected Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java new file mode 100644 index 0000000000..79bdd86658 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/AbstractJpaDao.java @@ -0,0 +1,56 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +public class AbstractJpaDao extends AbstractDao implements IOperations { + + @PersistenceContext(unitName = "jpaEntityManager") + private EntityManager em; + + // API + + @Override + public T findOne(final long id) { + return em.find(clazz, Long.valueOf(id).intValue()); + } + + @Override + public List findAll() { + final CriteriaBuilder cb = em.getCriteriaBuilder(); + final CriteriaQuery cq = cb.createQuery(clazz); + final Root rootEntry = cq.from(clazz); + final CriteriaQuery all = cq.select(rootEntry); + final TypedQuery allQuery = em.createQuery(all); + return allQuery.getResultList(); + } + + @Override + public void create(final T entity) { + em.persist(entity); + } + + @Override + public T update(final T entity) { + em.merge(entity); + return entity; + } + + @Override + public void delete(final T entity) { + em.remove(entity); + } + + @Override + public void deleteById(final long entityId) { + delete(findOne(entityId)); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java new file mode 100644 index 0000000000..18b16fa033 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java @@ -0,0 +1,13 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Repository; + +@Repository +@Scope(BeanDefinition.SCOPE_PROTOTYPE) +public class GenericHibernateDao extends AbstractHibernateDao implements IGenericDao { + // +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java new file mode 100644 index 0000000000..169d3fed72 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IAuditOperations.java @@ -0,0 +1,14 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +public interface IAuditOperations { + + List getEntitiesAtRevision(Number revision); + + List getEntitiesModifiedAtRevision(Number revision); + + List getRevisions(); + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java new file mode 100644 index 0000000000..8d8af18394 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java @@ -0,0 +1,7 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; + +public interface IGenericDao extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IOperations.java new file mode 100644 index 0000000000..4ef99221ab --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/common/IOperations.java @@ -0,0 +1,20 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + void create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java new file mode 100644 index 0000000000..e12b6ae2da --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarAuditableDao.java @@ -0,0 +1,28 @@ +package com.baeldung.persistence.dao.impl; + +import java.util.List; + +import com.baeldung.persistence.dao.IBarAuditableDao; +import com.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; +import com.baeldung.persistence.model.Bar; + +public class BarAuditableDao extends AbstractHibernateAuditableDao implements IBarAuditableDao { + + public BarAuditableDao() { + super(); + + setClazz(Bar.class); + } + + // API + + @Override + public List getRevisions() { + final List resultList = super.getRevisions(); + for (final Bar bar : resultList) { + bar.getFooSet().size(); // force FooSet initialization + } + return resultList; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java new file mode 100644 index 0000000000..0ead802dc5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarDao.java @@ -0,0 +1,19 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.model.Bar; +import org.springframework.stereotype.Repository; + +@Repository +public class BarDao extends AbstractHibernateDao implements IBarDao { + + public BarDao() { + super(); + + setClazz(Bar.class); + } + + // API + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java new file mode 100644 index 0000000000..e0fa382d41 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/BarJpaDao.java @@ -0,0 +1,19 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.dao.common.AbstractJpaDao; +import com.baeldung.persistence.model.Bar; +import org.springframework.stereotype.Repository; + +@Repository +public class BarJpaDao extends AbstractJpaDao implements IBarDao { + + public BarJpaDao() { + super(); + + setClazz(Bar.class); + } + + // API + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java new file mode 100644 index 0000000000..b55da6e43a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ChildDao.java @@ -0,0 +1,19 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.dao.IChildDao; +import org.springframework.stereotype.Repository; + +@Repository +public class ChildDao extends AbstractHibernateDao implements IChildDao { + + public ChildDao() { + super(); + + setClazz(Child.class); + } + + // API + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java new file mode 100644 index 0000000000..05064c1478 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooAuditableDao.java @@ -0,0 +1,17 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.dao.IFooAuditableDao; + +public class FooAuditableDao extends AbstractHibernateAuditableDao implements IFooAuditableDao { + + public FooAuditableDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java new file mode 100644 index 0000000000..787c449b1d --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java @@ -0,0 +1,19 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.model.Foo; +import org.springframework.stereotype.Repository; + +@Repository +public class FooDao extends AbstractHibernateDao implements IFooDao { + + public FooDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java new file mode 100644 index 0000000000..4602b5f30e --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/dao/impl/ParentDao.java @@ -0,0 +1,19 @@ +package com.baeldung.persistence.dao.impl; + +import com.baeldung.persistence.dao.IParentDao; +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.model.Parent; +import org.springframework.stereotype.Repository; + +@Repository +public class ParentDao extends AbstractHibernateDao implements IParentDao { + + public ParentDao() { + super(); + + setClazz(Parent.class); + } + + // API + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java new file mode 100644 index 0000000000..c7f05254cc --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java @@ -0,0 +1,242 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; +import java.util.Date; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; + +import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import com.google.common.collect.Sets; + +@Entity +@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") +@Audited +@EntityListeners(AuditingEntityListener.class) +public class Bar implements Serializable { + + private static Logger logger = Logger.getLogger(Bar.class); + + public enum OPERATION { + INSERT, UPDATE, DELETE; + private String value; + + OPERATION() { + value = toString(); + } + + public String getValue() { + return value; + } + + public static OPERATION parse(final String value) { + OPERATION operation = null; + for (final OPERATION op : OPERATION.values()) { + if (op.getValue().equals(value)) { + operation = op; + break; + } + } + return operation; + } + }; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private int id; + + @Column(name = "name") + private String name; + + @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @OrderBy(clause = "NAME DESC") + // @NotAudited + private Set fooSet = Sets.newHashSet(); + + @Column(name = "operation") + private String operation; + + @Column(name = "timestamp") + private long timestamp; + + @Column(name = "created_date", updatable = false, nullable = false) + @CreatedDate + private long createdDate; + + @Column(name = "modified_date") + @LastModifiedDate + private long modifiedDate; + + @Column(name = "created_by") + @CreatedBy + private String createdBy; + + @Column(name = "modified_by") + @LastModifiedBy + private String modifiedBy; + + public Bar() { + super(); + } + + public Bar(final String name) { + super(); + + this.name = name; + } + + // API + + public Set getFooSet() { + return fooSet; + } + + public void setFooSet(final Set fooSet) { + this.fooSet = fooSet; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public OPERATION getOperation() { + return OPERATION.parse(operation); + } + + public void setOperation(final OPERATION operation) { + this.operation = operation.getValue(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final long createdDate) { + this.createdDate = createdDate; + } + + public long getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(final long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(final String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public void setOperation(final String operation) { + this.operation = operation; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Bar other = (Bar) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Bar [name=").append(name).append("]"); + return builder.toString(); + } + + @PrePersist + public void onPrePersist() { + logger.info("@PrePersist"); + audit(OPERATION.INSERT); + } + + @PreUpdate + public void onPreUpdate() { + logger.info("@PreUpdate"); + audit(OPERATION.UPDATE); + } + + @PreRemove + public void onPreRemove() { + logger.info("@PreRemove"); + audit(OPERATION.DELETE); + } + + private void audit(final OPERATION operation) { + setOperation(operation); + setTimestamp((new Date()).getTime()); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Book.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Book.java deleted file mode 100644 index 507043dd56..0000000000 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Book.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Book { - - @Id - private Long id; - - private String title; - - private String author; - - public Long getId() { - return id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - -} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java new file mode 100644 index 0000000000..19cfb2e237 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Child.java @@ -0,0 +1,51 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Child implements Serializable { + + @Id + @GeneratedValue + private long id; + + @OneToOne(mappedBy = "child") + private Parent parent; + + public Child() { + super(); + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public Parent getParent() { + return parent; + } + + public void setParent(final Parent parent) { + this.parent = parent; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Child [id=").append(id).append("]"); + return builder.toString(); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..d36a1e58cf --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java @@ -0,0 +1,105 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; + +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.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; + +import org.hibernate.envers.Audited; + +@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) +@Entity +@Audited +// @Proxy(lazy = false) +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; + + @Column(name = "name") + private String name; + + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + this.name = name; + } + + // + + public Bar getBar() { + return bar; + } + + public void setBar(final Bar bar) { + this.bar = bar; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java new file mode 100644 index 0000000000..fa6948990b --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Parent.java @@ -0,0 +1,60 @@ +package com.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +@Entity +public class Parent implements Serializable { + + @Id + @GeneratedValue + private long id; + + @OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH }) + @JoinColumn(name = "child_fk") + private Child child; + + public Parent() { + super(); + } + + public Parent(final Child child) { + super(); + + this.child = child; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public Child getChild() { + return child; + } + + public void setChild(final Child child) { + this.child = child; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Parent [id=").append(id).append("]"); + return builder.toString(); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Person.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Person.java new file mode 100644 index 0000000000..6a95a7acf5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Person.java @@ -0,0 +1,31 @@ +package com.baeldung.persistence.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private Long id; + + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java new file mode 100644 index 0000000000..33e5634d12 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarAuditableService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.dao.common.IAuditOperations; +import com.baeldung.persistence.model.Bar; + +public interface IBarAuditableService extends IBarService, IAuditOperations { + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarService.java new file mode 100644 index 0000000000..21185b5990 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IBarService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.model.Bar; + +public interface IBarService extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IChildService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IChildService.java new file mode 100644 index 0000000000..afe67a70c2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IChildService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IChildService extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java new file mode 100644 index 0000000000..b787e7fe91 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooAuditableService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.dao.common.IAuditOperations; +import com.baeldung.persistence.model.Foo; + +public interface IFooAuditableService extends IFooService, IAuditOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooService.java new file mode 100644 index 0000000000..ffdb53964a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IFooService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IFooService extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IParentService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IParentService.java new file mode 100644 index 0000000000..f941416aac --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/IParentService.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.service; + +import com.baeldung.persistence.model.Parent; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IParentService extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java new file mode 100644 index 0000000000..2695d7760a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateAuditableService.java @@ -0,0 +1,30 @@ +package com.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import com.baeldung.persistence.dao.common.IAuditOperations; +import com.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "hibernateTransactionManager") +public abstract class AbstractHibernateAuditableService extends AbstractHibernateService implements IOperations, IAuditOperations { + + @Override + public List getEntitiesAtRevision(final Number revision) { + return getAuditableDao().getEntitiesAtRevision(revision); + } + + @Override + public List getEntitiesModifiedAtRevision(final Number revision) { + return getAuditableDao().getEntitiesModifiedAtRevision(revision); + } + + @Override + public List getRevisions() { + return getAuditableDao().getRevisions(); + } + + abstract protected IAuditOperations getAuditableDao(); + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java new file mode 100644 index 0000000000..02b8ccf48b --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractHibernateService.java @@ -0,0 +1,42 @@ +package com.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import com.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "hibernateTransactionManager") +public abstract class AbstractHibernateService extends AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return super.findOne(id); + } + + @Override + public List findAll() { + return super.findAll(); + } + + @Override + public void create(final T entity) { + super.create(entity); + } + + @Override + public T update(final T entity) { + return super.update(entity); + } + + @Override + public void delete(final T entity) { + super.delete(entity); + } + + @Override + public void deleteById(final long entityId) { + super.deleteById(entityId); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java new file mode 100644 index 0000000000..a1c6fe9edf --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractJpaService.java @@ -0,0 +1,42 @@ +package com.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import com.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "jpaTransactionManager") +public abstract class AbstractJpaService extends AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return super.findOne(id); + } + + @Override + public List findAll() { + return super.findAll(); + } + + @Override + public void create(final T entity) { + super.create(entity); + } + + @Override + public T update(final T entity) { + return super.update(entity); + } + + @Override + public void delete(final T entity) { + super.delete(entity); + } + + @Override + public void deleteById(final long entityId) { + super.deleteById(entityId); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractService.java new file mode 100644 index 0000000000..9b001b1fac --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractService.java @@ -0,0 +1,42 @@ +package com.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import com.baeldung.persistence.dao.common.IOperations; + +public abstract class AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findOne(id); + } + + @Override + public List findAll() { + return getDao().findAll(); + } + + @Override + public void create(final T entity) { + getDao().create(entity); + } + + @Override + public T update(final T entity) { + return getDao().update(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract IOperations getDao(); + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java new file mode 100644 index 0000000000..73fe27e9ec --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/common/AbstractSpringDataJpaService.java @@ -0,0 +1,48 @@ +package com.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; +import java.util.Optional; + +import com.baeldung.persistence.dao.common.IOperations; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +import com.google.common.collect.Lists; + +@Transactional(value = "jpaTransactionManager") +public abstract class AbstractSpringDataJpaService implements IOperations { + + @Override + public T findOne(final long id) { + Optional opt = getDao().findById(Long.valueOf(id)); + return opt.get(); + } + + @Override + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public void create(final T entity) { + getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(Long.valueOf(entityId)); + } + + protected abstract CrudRepository getDao(); +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java new file mode 100644 index 0000000000..d84c28caa5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarAuditableService.java @@ -0,0 +1,41 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.dao.common.IAuditOperations; +import com.baeldung.persistence.service.common.AbstractHibernateAuditableService; +import com.baeldung.persistence.dao.IBarAuditableDao; +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.service.IBarAuditableService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarAuditableService extends AbstractHibernateAuditableService implements IBarAuditableService { + + @Autowired + @Qualifier("barHibernateDao") + private IBarDao dao; + + @Autowired + @Qualifier("barHibernateAuditableDao") + private IBarAuditableDao auditDao; + + public BarAuditableService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + + @Override + protected IAuditOperations getAuditableDao() { + return auditDao; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java new file mode 100644 index 0000000000..1c1b7a2274 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarJpaService.java @@ -0,0 +1,30 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.persistence.service.common.AbstractJpaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarJpaService extends AbstractJpaService implements IBarService { + + @Autowired + @Qualifier("barJpaDao") + private IBarDao dao; + + public BarJpaService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarService.java new file mode 100644 index 0000000000..32d1f919c5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarService.java @@ -0,0 +1,30 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.persistence.service.common.AbstractHibernateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarService extends AbstractHibernateService implements IBarService { + + @Autowired + @Qualifier("barHibernateDao") + private IBarDao dao; + + public BarService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java new file mode 100644 index 0000000000..4a55d08a35 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/BarSpringDataJpaService.java @@ -0,0 +1,26 @@ +package com.baeldung.persistence.service.impl; + +import java.io.Serializable; + +import com.baeldung.persistence.service.common.AbstractSpringDataJpaService; +import com.baeldung.persistence.dao.IBarCrudRepository; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.service.IBarService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.repository.CrudRepository; + +public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { + + @Autowired + private IBarCrudRepository dao; + + public BarSpringDataJpaService() { + super(); + } + + @Override + protected CrudRepository getDao() { + return dao; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ChildService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ChildService.java new file mode 100644 index 0000000000..417fe2c49a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ChildService.java @@ -0,0 +1,28 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.service.IChildService; +import com.baeldung.persistence.dao.IChildDao; +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.service.common.AbstractHibernateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ChildService extends AbstractHibernateService implements IChildService { + + @Autowired + private IChildDao dao; + + public ChildService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java new file mode 100644 index 0000000000..45ad315c42 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooAuditableService.java @@ -0,0 +1,41 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.dao.common.IAuditOperations; +import com.baeldung.persistence.service.IFooAuditableService; +import com.baeldung.persistence.service.common.AbstractHibernateAuditableService; +import com.baeldung.persistence.dao.IFooAuditableDao; +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class FooAuditableService extends AbstractHibernateAuditableService implements IFooAuditableService { + + @Autowired + @Qualifier("fooHibernateDao") + private IFooDao dao; + + @Autowired + @Qualifier("fooHibernateAuditableDao") + private IFooAuditableDao auditDao; + + public FooAuditableService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + + @Override + protected IAuditOperations getAuditableDao() { + return auditDao; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooService.java new file mode 100644 index 0000000000..84cf018fee --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/FooService.java @@ -0,0 +1,30 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.persistence.service.common.AbstractHibernateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class FooService extends AbstractHibernateService implements IFooService { + + @Autowired + @Qualifier("fooHibernateDao") + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ParentService.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ParentService.java new file mode 100644 index 0000000000..078acfc369 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/service/impl/ParentService.java @@ -0,0 +1,28 @@ +package com.baeldung.persistence.service.impl; + +import com.baeldung.persistence.model.Parent; +import com.baeldung.persistence.service.IParentService; +import com.baeldung.persistence.dao.IParentDao; +import com.baeldung.persistence.dao.common.IOperations; +import com.baeldung.persistence.service.common.AbstractHibernateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ParentService extends AbstractHibernateService implements IParentService { + + @Autowired + private IParentDao dao; + + public ParentService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching.cfg.xml new file mode 100644 index 0000000000..1b9a4a191c --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching.cfg.xml @@ -0,0 +1,20 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + validate + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetchingLazy.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetchingLazy.cfg.xml new file mode 100644 index 0000000000..c5f608e1a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetchingLazy.cfg.xml @@ -0,0 +1,17 @@ + + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/test + root + iamtheking + org.hibernate.dialect.MySQLDialect + true + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching_create_queries.sql b/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching_create_queries.sql new file mode 100644 index 0000000000..b36d9828f1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/fetching_create_queries.sql @@ -0,0 +1,14 @@ +CREATE TABLE `user` ( + `user_id` int(10) NOT NULL AUTO_INCREMENT, + PRIMARY KEY (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ; + + +CREATE TABLE `user_order` ( + `ORDER_ID` int(10) NOT NULL AUTO_INCREMENT, + `USER_ID` int(10) NOT NULL DEFAULT '0', + PRIMARY KEY (`ORDER_ID`,`USER_ID`), + KEY `USER_ID` (`USER_ID`), + CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; + diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Config.xml new file mode 100644 index 0000000000..bbb61cb3e0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Config.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Configuration.xml new file mode 100644 index 0000000000..1870cfb917 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/hibernate5Configuration.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/immutable.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/main/resources/immutable.cfg.xml new file mode 100644 index 0000000000..fe1e3cb723 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/immutable.cfg.xml @@ -0,0 +1,38 @@ + + + + + + + + + org.hsqldb.jdbcDriver + jdbc:hsqldb:hsql:mem://localhost/xdb + sa + + + + 1 + + + org.hibernate.dialect.HSQLDialect + + + thread + + + org.hibernate.cache.NoCacheProvider + + + true + + + update + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/insert_statements.sql b/persistence-modules/spring-data-jpa-query-2/src/main/resources/insert_statements.sql new file mode 100644 index 0000000000..ae008f29bc --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/insert_statements.sql @@ -0,0 +1,31 @@ +insert into item (item_id, item_name, item_desc, item_price) +values(1,'item One', 'test 1', 35.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(2,'Pogo stick', 'Pogo stick', 466.12); +insert into item (item_id, item_name, item_desc, item_price) +values(3,'Raft', 'Raft', 345.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(4,'Skate Board', 'Skating', 135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(5,'Umbrella', 'Umbrella for Rain', 619.25); + +insert into item (item_id, item_name, item_desc, item_price) +values(6,'Glue', 'Glue for home', 432.73); + +insert into item (item_id, item_name, item_desc, item_price) +values(7,'Paint', 'Paint for Room', 1311.40); + +insert into item (item_id, item_name, item_desc, item_price) +values(8,'Red paint', 'Red paint for room', 1135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(9,'Household Chairs', 'Chairs for house', 25.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(10,'Office Chairs', 'Chairs for office', 395.98); + +insert into item (item_id, item_name, item_desc, item_price) +values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa-query-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-data-jpa-query-2/src/main/resources/persistence-mysql.properties new file mode 100644 index 0000000000..f6b6ab6fca --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/persistence-mysql.properties @@ -0,0 +1,13 @@ +# jdbc.X +jdbc.driverClassName=com.mysql.jdbc.Driver +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true +jdbc.user=tutorialuser +jdbc.pass=tutorialmy5ql + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop + +# envers.X +envers.audit_table_suffix=_audit_log diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/resources/stored_procedure.sql b/persistence-modules/spring-data-jpa-query-2/src/main/resources/stored_procedure.sql new file mode 100644 index 0000000000..9cedb75c37 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/stored_procedure.sql @@ -0,0 +1,20 @@ +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-data-jpa-query-2/src/main/resources/webSecurityConfig.xml b/persistence-modules/spring-data-jpa-query-2/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..e5c19a4ad7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java new file mode 100644 index 0000000000..65bf36f8bf --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.hibernate.fetching; + +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.view.FetchingAppView; +import org.hibernate.Hibernate; +import org.junit.Before; +import org.junit.Test; + +import java.util.Set; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class HibernateFetchingIntegrationTest { + + // this loads sample data in the database + @Before + public void addFecthingTestData() { + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } + + // testLazyFetching() tests the lazy loading + // Since it lazily loaded so orderDetalSetLazy won't + // be initialized + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); + } + + // testEagerFetching() tests the eager loading + // Since it eagerly loaded so orderDetalSetLazy would + // be initialized + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); + } +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java new file mode 100644 index 0000000000..f5c45a5d6f --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java @@ -0,0 +1,25 @@ +package com.baeldung.persistence; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +import com.baeldung.persistence.audit.AuditTestSuite; +import com.baeldung.persistence.hibernate.FooPaginationPersistenceIntegrationTest; +import com.baeldung.persistence.hibernate.FooSortingPersistenceIntegrationTest; +import com.baeldung.persistence.service.FooServiceBasicPersistenceIntegrationTest; +import com.baeldung.persistence.service.FooServicePersistenceIntegrationTest; +import com.baeldung.persistence.service.ParentServicePersistenceIntegrationTest; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ // @formatter:off + AuditTestSuite.class + ,FooServiceBasicPersistenceIntegrationTest.class + ,FooPaginationPersistenceIntegrationTest.class + ,FooServicePersistenceIntegrationTest.class + ,ParentServicePersistenceIntegrationTest.class + ,FooSortingPersistenceIntegrationTest.class + +}) // @formatter:on +public class IntegrationTestSuite { + // +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java new file mode 100644 index 0000000000..34c725d62b --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java @@ -0,0 +1,14 @@ +package com.baeldung.persistence.audit; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ // @formatter:off + EnversFooBarAuditIntegrationTest.class, + JPABarAuditIntegrationTest.class, + SpringDataJPABarAuditIntegrationTest.class +}) // @formatter:on +public class AuditTestSuite { + // +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java new file mode 100644 index 0000000000..444324dafc --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -0,0 +1,146 @@ +package com.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IBarAuditableService; +import com.baeldung.persistence.service.IFooAuditableService; +import com.baeldung.spring.config.PersistenceTestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class EnversFooBarAuditIntegrationTest { + + private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("fooHibernateAuditableService") + private IFooAuditableService fooService; + + @Autowired + @Qualifier("barHibernateAuditableService") + private IBarAuditableService barService; + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + makeRevisions(); + session = sessionFactory.openSession(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + session.close(); + } + + private void makeRevisions() { + final Bar bar = rev1(); + rev2(bar); + rev3(bar); + rev4(bar); + } + + // REV #1: insert BAR & FOO1 + private Bar rev1() { + final Bar bar = new Bar("BAR"); + final Foo foo1 = new Foo("FOO1"); + foo1.setBar(bar); + fooService.create(foo1); + return bar; + } + + // REV #2: insert FOO2 & update BAR + private void rev2(final Bar bar) { + final Foo foo2 = new Foo("FOO2"); + foo2.setBar(bar); + fooService.create(foo2); + } + + // REV #3: update BAR + private void rev3(final Bar bar) { + + bar.setName("BAR1"); + barService.update(bar); + } + + // REV #4: insert FOO3 & update BAR + private void rev4(final Bar bar) { + + final Foo foo3 = new Foo("FOO3"); + foo3.setBar(bar); + fooService.create(foo3); + } + + @Test + public final void whenFooBarsModified_thenFooBarsAudited() { + + List barRevisionList; + List fooRevisionList; + + // test Bar revisions + + barRevisionList = barService.getRevisions(); + + assertNotNull(barRevisionList); + assertEquals(4, barRevisionList.size()); + + assertEquals("BAR", barRevisionList.get(0).getName()); + assertEquals("BAR", barRevisionList.get(1).getName()); + assertEquals("BAR1", barRevisionList.get(2).getName()); + assertEquals("BAR1", barRevisionList.get(3).getName()); + + assertEquals(1, barRevisionList.get(0).getFooSet().size()); + assertEquals(2, barRevisionList.get(1).getFooSet().size()); + assertEquals(2, barRevisionList.get(2).getFooSet().size()); + assertEquals(3, barRevisionList.get(3).getFooSet().size()); + + // test Foo revisions + + fooRevisionList = fooService.getRevisions(); + assertNotNull(fooRevisionList); + assertEquals(3, fooRevisionList.size()); + assertEquals("FOO1", fooRevisionList.get(0).getName()); + assertEquals("FOO2", fooRevisionList.get(1).getName()); + assertEquals("FOO3", fooRevisionList.get(2).getName()); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java new file mode 100644 index 0000000000..f591773cde --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java @@ -0,0 +1,104 @@ +package com.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.model.Bar.OPERATION; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.spring.config.PersistenceTestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class JPABarAuditIntegrationTest { + + private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barJpaService") + private IBarService barService; + + @Autowired + @Qualifier("jpaEntityManager") + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + public final void whenBarsModified_thenBarsAudited() { + + // insert BAR1 + Bar bar1 = new Bar("BAR1"); + barService.create(bar1); + + // update BAR1 + bar1.setName("BAR1a"); + barService.update(bar1); + + // insert BAR2 + Bar bar2 = new Bar("BAR2"); + barService.create(bar2); + + // update BAR1 + bar1.setName("BAR1b"); + barService.update(bar1); + + // get BAR1 and BAR2 from the DB and check the audit values + // detach instances from persistence context to make sure we fire db + em.detach(bar1); + em.detach(bar2); + bar1 = barService.findOne(bar1.getId()); + bar2 = barService.findOne(bar2.getId()); + + assertNotNull(bar1); + assertNotNull(bar2); + assertEquals(OPERATION.UPDATE, bar1.getOperation()); + assertEquals(OPERATION.INSERT, bar2.getOperation()); + assertTrue(bar1.getTimestamp() > bar2.getTimestamp()); + + barService.deleteById(bar1.getId()); + barService.deleteById(bar2.getId()); + + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java new file mode 100644 index 0000000000..0603067810 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java @@ -0,0 +1,78 @@ +package com.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.spring.config.PersistenceTestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringDataJPABarAuditIntegrationTest { + + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barSpringDataJpaService") + private IBarService barService; + + @Autowired + @Qualifier("jpaEntityManager") + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + @WithMockUser(username = "tutorialuser") + public final void whenBarsModified_thenBarsAudited() { + Bar bar = new Bar("BAR1"); + barService.create(bar); + assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + bar.setName("BAR2"); + bar = barService.update(bar); + assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + } +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java new file mode 100644 index 0000000000..da840dc027 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java @@ -0,0 +1,101 @@ +package com.baeldung.persistence.hibernate; + +import java.util.List; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.model.Bar; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.google.common.collect.Lists; + +public class FooFixtures { + private SessionFactory sessionFactory; + + public FooFixtures(final SessionFactory sessionFactory) { + super(); + + this.sessionFactory = sessionFactory; + } + + // API + + public void createBars() { + Session session = null; + Transaction tx = null; + session = sessionFactory.openSession(); + tx = session.getTransaction(); + try { + tx.begin(); + for (int i = 156; i < 160; i++) { + final Bar bar = new Bar(); + bar.setName("Bar_" + i); + final Foo foo = new Foo("Foo_" + (i + 120)); + foo.setBar(bar); + session.save(foo); + final Foo foo2 = new Foo(null); + if (i % 2 == 0) + foo2.setName("LuckyFoo" + (i + 120)); + foo2.setBar(bar); + session.save(foo2); + bar.getFooSet().add(foo); + bar.getFooSet().add(foo2); + session.merge(bar); + } + tx.commit(); + session.flush(); + } catch (final HibernateException he) { + if (tx != null) + tx.rollback(); + System.out.println("Not able to open session"); + he.printStackTrace(); + } catch (final Exception e) { + e.printStackTrace(); + } finally { + if (session != null) + session.close(); + } + + } + + public void createFoos() { + Session session = null; + Transaction tx = null; + session = sessionFactory.openSession(); + tx = session.getTransaction(); + final List fooList = Lists.newArrayList(); + for (int i = 35; i < 46; i++) { + + final Foo foo = new Foo(); + foo.setName("Foo_" + (i + 120)); + final Bar bar = new Bar("bar_" + i); + bar.getFooSet().add(foo); + foo.setBar(bar); + fooList.add(foo); + + } + try { + tx.begin(); + for (final Foo foo : fooList) { + + session.save(foo.getBar()); + session.save(foo); + } + tx.commit(); + session.flush(); + } catch (final HibernateException he) { + if (tx != null) + tx.rollback(); + System.out.println("Not able to open session"); + he.printStackTrace(); + } catch (final Exception e) { + e.printStackTrace(); + } finally { + if (session != null) + session.close(); + } + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java new file mode 100644 index 0000000000..fd7bc4aabf --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java @@ -0,0 +1,185 @@ +package com.baeldung.persistence.hibernate; + +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 org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.ScrollMode; +import org.hibernate.ScrollableResults; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Projections; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.spring.config.PersistenceTestConfig; +import com.google.common.collect.Lists; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class FooPaginationPersistenceIntegrationTest { + + @Autowired + private IFooService fooService; + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + // tests + + @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))); + } + } + + session = sessionFactory.openSession(); + } + + @After + public final void after() { + session.close(); + } + + // tests + + @Test + public final void whenContextIsBootstrapped_thenNoExceptions() { + // + } + + @SuppressWarnings("unchecked") + @Test + public final void whenRetrievingPaginatedEntities_thenCorrectSize() { + final int pageNumber = 1; + final int pageSize = 10; + + final Query query = session.createQuery("From Foo"); + query.setFirstResult((pageNumber - 1) * pageSize); + query.setMaxResults(pageSize); + final List fooList = query.list(); + + assertThat(fooList, hasSize(pageSize)); + } + + @SuppressWarnings("unchecked") + @Test + public final void whenRetrievingAllPages_thenCorrect() { + int pageNumber = 1; + final int pageSize = 10; + + final String countQ = "Select count (f.id) from Foo f"; + final Query countQuery = session.createQuery(countQ); + final Long countResult = (Long) countQuery.uniqueResult(); + + final List fooList = Lists.newArrayList(); + int totalEntities = 0; + final Query query = session.createQuery("From Foo"); + while (totalEntities < countResult) { + query.setFirstResult((pageNumber - 1) * pageSize); + query.setMaxResults(pageSize); + fooList.addAll(query.list()); + totalEntities = fooList.size(); + pageNumber++; + } + } + + @SuppressWarnings("unchecked") + @Test + public final void whenRetrievingLastPage_thenCorrectSize() { + final int pageSize = 10; + + final String countQ = "Select count (f.id) from Foo f"; + final Query countQuery = session.createQuery(countQ); + final Long countResults = (Long) countQuery.uniqueResult(); + final int lastPageNumber = (int) (Math.ceil(countResults / pageSize)); + + final Query selectQuery = session.createQuery("From Foo"); + selectQuery.setFirstResult((lastPageNumber - 1) * pageSize); + selectQuery.setMaxResults(pageSize); + final List lastPage = selectQuery.list(); + + assertThat(lastPage, hasSize(lessThan(pageSize + 1))); + } + + // testing - scrollable + + @Test + public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() { + final int pageSize = 10; + final String hql = "FROM Foo f order by f.name"; + final Query query = session.createQuery(hql); + + final ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY); + + // resultScroll.last(); + // final int totalResults = resultScroll.getRowNumber() + 1; + + resultScroll.first(); + resultScroll.scroll(0); + final List fooPage = Lists.newArrayList(); + int i = 0; + while (pageSize > i++) { + fooPage.add((Foo) resultScroll.get(0)); + if (!resultScroll.next()) { + break; + } + } + + assertThat(fooPage, hasSize(lessThan(10 + 1))); + } + + @SuppressWarnings("unchecked") + @Test + public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() { + final int pageSize = 10; + + final Criteria criteria = session.createCriteria(Foo.class); + criteria.setFirstResult(0); + criteria.setMaxResults(pageSize); + final List firstPage = criteria.list(); + + assertThat(firstPage, hasSize(pageSize)); + } + + @SuppressWarnings("unchecked") + @Test + public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() { + final Criteria criteriaCount = session.createCriteria(Foo.class); + criteriaCount.setProjection(Projections.rowCount()); + final Long count = (Long) criteriaCount.uniqueResult(); + + int pageNumber = 1; + final int pageSize = 10; + final List fooList = Lists.newArrayList(); + + final Criteria criteria = session.createCriteria(Foo.class); + int totalEntities = 0; + while (totalEntities < count.intValue()) { + criteria.setFirstResult((pageNumber - 1) * pageSize); + criteria.setMaxResults(pageSize); + fooList.addAll(criteria.list()); + totalEntities = fooList.size(); + pageNumber++; + } + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java new file mode 100644 index 0000000000..8173088af0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java @@ -0,0 +1,174 @@ +package com.baeldung.persistence.hibernate; + +import static org.junit.Assert.assertNull; + +import java.util.List; +import java.util.Set; + +import org.hibernate.Criteria; +import org.hibernate.NullPrecedence; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Order; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.config.PersistenceTestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +@SuppressWarnings("unchecked") +public class FooSortingPersistenceIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + @Before + public void before() { + session = sessionFactory.openSession(); + + session.beginTransaction(); + + final FooFixtures fooData = new FooFixtures(sessionFactory); + fooData.createBars(); + } + + @After + public void after() { + session.getTransaction().commit(); + session.close(); + } + + @Test + public final void whenHQlSortingByOneAttribute_thenPrintSortedResults() { + final String hql = "FROM Foo f ORDER BY f.name"; + final Query query = session.createQuery(hql); + final List fooList = query.list(); + for (final Foo foo : fooList) { + System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + } + } + + @Test + public final void whenHQlSortingByStringNullLast_thenLastNull() { + final String hql = "FROM Foo f ORDER BY f.name NULLS LAST"; + final Query query = session.createQuery(hql); + final List fooList = query.list(); + + assertNull(fooList.get(fooList.toArray().length - 1).getName()); + for (final Foo foo : fooList) { + System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + } + } + + @Test + public final void whenSortingByStringNullsFirst_thenReturnNullsFirst() { + final String hql = "FROM Foo f ORDER BY f.name NULLS FIRST"; + final Query query = session.createQuery(hql); + final List fooList = query.list(); + assertNull(fooList.get(0).getName()); + for (final Foo foo : fooList) { + System.out.println("Name:" + foo.getName()); + + } + } + + @Test + public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() { + final String hql = "FROM Foo f ORDER BY f.name ASC"; + final Query query = session.createQuery(hql); + final List fooList = query.list(); + for (final Foo foo : fooList) { + System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + } + } + + @Test + public final void whenHQlSortingByMultipleAttributes_thenSortedResults() { + final String hql = "FROM Foo f ORDER BY f.name, f.id"; + final Query query = session.createQuery(hql); + final List fooList = query.list(); + for (final Foo foo : fooList) { + System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + } + } + + @Test + public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() { + final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC"; + final Query query = session.createQuery(hql); + final List fooList = query.list(); + for (final Foo foo : fooList) { + System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + } + } + + @Test + public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() { + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); + criteria.addOrder(Order.asc("id")); + final List fooList = criteria.list(); + for (final Foo foo : fooList) { + System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + } + } + + @Test + public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() { + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); + criteria.addOrder(Order.asc("name")); + criteria.addOrder(Order.asc("id")); + final List fooList = criteria.list(); + for (final Foo foo : fooList) { + System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + } + } + + @Test + public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); + criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); + final List fooList = criteria.list(); + assertNull(fooList.get(fooList.toArray().length - 1).getName()); + for (final Foo foo : fooList) { + System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + } + } + + @Test + public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); + criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); + final List fooList = criteria.list(); + assertNull(fooList.get(0).getName()); + for (final Foo foo : fooList) { + System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + } + } + + @Test + public final void whenSortingBars_thenBarsWithSortedFoos() { + final String hql = "FROM Bar b ORDER BY b.id"; + final Query query = session.createQuery(hql); + final List barList = query.list(); + for (final Bar bar : barList) { + final Set fooSet = bar.getFooSet(); + System.out.println("Bar Id:" + bar.getId()); + for (final Foo foo : fooSet) { + System.out.println("FooName:" + foo.getName()); + } + } + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java new file mode 100644 index 0000000000..146f8e9622 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java @@ -0,0 +1,55 @@ +package com.baeldung.persistence.service; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.config.PersistenceTestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class FooServiceBasicPersistenceIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + @Autowired + private IFooService fooService; + + private Session session; + + // tests + + @Before + public final void before() { + session = sessionFactory.openSession(); + } + + @After + public final void after() { + session.close(); + } + + // tests + + @Test + public final void whenContextIsBootstrapped_thenNoExceptions() { + // + } + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + fooService.create(new Foo(randomAlphabetic(6))); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..6d426849a6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.persistence.service; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.dao.DataAccessException; +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.model.Foo; +import com.baeldung.spring.config.PersistenceTestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class FooServicePersistenceIntegrationTest { + + @Autowired + @Qualifier("fooHibernateService") + 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) + @Ignore("work in progress") + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenEntityWithLongNameIsCreated_thenDataException() { + service.create(new Foo(randomAlphabetic(2048))); + } + + @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); + } + + @Test(expected = DataAccessException.class) + public final void temp_whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo(randomAlphabetic(2048))); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java new file mode 100644 index 0000000000..8bf33c4110 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java @@ -0,0 +1,121 @@ +package com.baeldung.persistence.service; + +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertEquals; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.exception.SQLGrammarException; +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; + +import com.baeldung.config.PersistenceConfig; +import com.baeldung.persistence.model.Foo; + +@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 IFooService fooService; + + private Session session; + + @Before + public final void before() { + session = sessionFactory.openSession(); + Assume.assumeTrue(getAllFoosExists()); + Assume.assumeTrue(getFoosByNameExists()); + } + + private boolean getFoosByNameExists() { + try { + Query 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 { + Query 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 + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + @SuppressWarnings("unchecked") + 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 + Query namedQuery = session.getNamedQuery("callGetAllFoos"); + @SuppressWarnings("unchecked") + 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() + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); + @SuppressWarnings("unchecked") + List allFoosByName = sqlQuery.list(); + for (Foo foo : allFoosByName) { + LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); + } + + // Stored procedure getFoosByName using getNamedQuery() + Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); + @SuppressWarnings("unchecked") + List allFoosByName2 = namedQuery.list(); + for (Foo foo : allFoosByName2) { + LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); + } + + } +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..5a73e39ca2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.persistence.service; + +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.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.model.Parent; +import com.baeldung.spring.config.PersistenceTestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class ParentServicePersistenceIntegrationTest { + + @Autowired + private IParentService service; + + @Autowired + private IChildService childService; + + // tests + + @Test + public final void whenContextIsBootstrapped_thenNoExceptions() { + // + } + + @Test + public final void whenOneToOneEntitiesAreCreated_thenNoExceptions() { + final Child childEntity = new Child(); + childService.create(childEntity); + + final Parent parentEntity = new Parent(childEntity); + service.create(parentEntity); + + System.out.println("Child = " + childService.findOne(childEntity.getId())); + System.out.println("Child - parent = " + childService.findOne(childEntity.getId()).getParent()); + + System.out.println("Parent = " + service.findOne(parentEntity.getId())); + System.out.println("Parent - child = " + service.findOne(parentEntity.getId()).getChild()); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenChildIsDeletedWhileParentStillHasForeignKeyToIt_thenDataException() { + final Child childEntity = new Child(); + childService.create(childEntity); + + final Parent parentEntity = new Parent(childEntity); + service.create(parentEntity); + + childService.delete(childEntity); + } + + @Test + public final void whenChildIsDeletedAfterTheParent_thenNoExceptions() { + final Child childEntity = new Child(); + childService.create(childEntity); + + final Parent parentEntity = new Parent(childEntity); + service.create(parentEntity); + + service.delete(parentEntity); + childService.delete(childEntity); + } + +} diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java new file mode 100644 index 0000000000..34301741fe --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java @@ -0,0 +1,179 @@ +package com.baeldung.spring.config; + +import java.util.Properties; + +import javax.sql.DataSource; + +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.data.jpa.repository.config.EnableJpaRepositories; +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 com.baeldung.persistence.dao.IBarAuditableDao; +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.dao.IFooAuditableDao; +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.dao.impl.BarAuditableDao; +import com.baeldung.persistence.dao.impl.BarDao; +import com.baeldung.persistence.dao.impl.BarJpaDao; +import com.baeldung.persistence.dao.impl.FooAuditableDao; +import com.baeldung.persistence.dao.impl.FooDao; +import com.baeldung.persistence.service.IBarAuditableService; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.persistence.service.IFooAuditableService; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.persistence.service.impl.BarAuditableService; +import com.baeldung.persistence.service.impl.BarJpaService; +import com.baeldung.persistence.service.impl.BarSpringDataJpaService; +import com.baeldung.persistence.service.impl.FooAuditableService; +import com.baeldung.persistence.service.impl.FooService; +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager", entityManagerFactoryRef = "jpaEntityManager") +@EnableJpaAuditing +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "com.baeldung.persistence" }) +public class PersistenceTestConfig { + + @Autowired + private Environment env; + + public PersistenceTestConfig() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean("jpaEntityManager") + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(restDataSource()); + emf.setPackagesToScan(new String[] { "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 IBarService barJpaService() { + return new BarJpaService(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooHibernateService() { + return new FooService(); + } + + @Bean + public IBarAuditableService barHibernateAuditableService() { + return new BarAuditableService(); + } + + @Bean + public IFooAuditableService fooHibernateAuditableService() { + return new FooAuditableService(); + } + + @Bean + public IBarDao barJpaDao() { + return new BarJpaDao(); + } + + @Bean + public IBarDao barHibernateDao() { + return new BarDao(); + } + + @Bean + public IBarAuditableDao barHibernateAuditableDao() { + return new BarAuditableDao(); + } + + @Bean + public IFooDao fooHibernateDao() { + return new FooDao(); + } + + @Bean + public IFooAuditableDao fooHibernateAuditableDao() { + return new FooAuditableDao(); + } + + private final 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"); + // hibernateProperties.setProperty("hibernate.format_sql", "true"); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "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-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java index 38fd804195..b1158b3dae 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java @@ -6,6 +6,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.spring.data.jpa.query.datetime.Article; +import com.baeldung.spring.data.jpa.query.datetime.ArticleRepository; + import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml new file mode 100644 index 0000000000..55a3aeb51c --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml @@ -0,0 +1,19 @@ + + + + + + org.h2.Driver + jdbc:h2:mem:testdb + sa + + org.hibernate.dialect.H2Dialect + update + true + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml new file mode 100644 index 0000000000..8fcf578660 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml @@ -0,0 +1,19 @@ + + + + + + org.h2.Driver + jdbc:h2:mem:testdb + sa + + org.hibernate.dialect.H2Dialect + update + true + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/resources/persistence-h2.properties b/persistence-modules/spring-data-jpa-query-2/src/test/resources/persistence-h2.properties new file mode 100644 index 0000000000..911619193b --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/test/resources/persistence-h2.properties @@ -0,0 +1,13 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:test +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop + +# envers.X +envers.audit_table_suffix=_audit_log From 6d9024049e1cdc01f22c77f3d9160cf3d8e0d410 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 28 Sep 2020 23:18:18 +0530 Subject: [PATCH 6/6] JAVA-2432: Added link to existing article --- persistence-modules/spring-hibernate-5/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index 6d7526a13b..c7506026dd 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -12,4 +12,5 @@ This module contains articles about Hibernate 5 with Spring. - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) -- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) \ No newline at end of file +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) +- [Guide to Hibernate 5 with Spring](https://www.baeldung.com/hibernate-4-spring) \ No newline at end of file