JAVA-2432: Moved 5 articles to spring-data-jpa-query-2
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -18,6 +18,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
@@ -28,6 +32,55 @@
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-envers</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.transaction</groupId>
|
||||
<artifactId>jta</artifactId>
|
||||
<version>${jta.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-dbcp</artifactId>
|
||||
<version>${tomcat-dbcp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-envers</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -35,5 +88,10 @@
|
||||
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
<junit.version>4.13</junit.version>
|
||||
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
|
||||
<jta.version>1.1</jta.version>
|
||||
<guava.version>21.0</guava.version>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>5.2.10.Final</hibernate.version>
|
||||
</properties>
|
||||
</project>
|
||||
+186
@@ -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<String> 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;
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -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<String> {
|
||||
|
||||
@Override
|
||||
public Optional<String> getCurrentAuditor() {
|
||||
return Optional.ofNullable(SecurityContextHolder.getContext())
|
||||
.map(e -> e.getAuthentication())
|
||||
.map(Authentication::getName);
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -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;
|
||||
}
|
||||
}
|
||||
+71
@@ -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> 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<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||
this.orderDetail = orderDetail;
|
||||
}
|
||||
|
||||
}
|
||||
+71
@@ -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> 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<OrderDetail> getOrderDetail() {
|
||||
return orderDetail;
|
||||
}
|
||||
|
||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||
this.orderDetail = orderDetail;
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -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<OrderDetail> lazyLoaded() {
|
||||
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
|
||||
List<UserLazy> 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<OrderDetail> eagerLoaded() {
|
||||
final Session sessionEager = HibernateUtil.getHibernateSession();
|
||||
// data should be loaded in the following line
|
||||
// also note the queries generated
|
||||
List<UserEager> 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();
|
||||
|
||||
}
|
||||
}
|
||||
-9
@@ -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<Book, Long>, BookRepositoryCustom, JpaSpecificationExecutor<Book> {
|
||||
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.persistence.dao;
|
||||
|
||||
import com.baeldung.persistence.model.Book;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface BookRepositoryCustom {
|
||||
|
||||
List<Book> findBooksByAuthorNameAndTitle(String authorName, String title);
|
||||
|
||||
}
|
||||
-44
@@ -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<Book> findBooksByAuthorNameAndTitle(String authorName, String title) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Book> cq = cb.createQuery(Book.class);
|
||||
|
||||
Root<Book> book = cq.from(Book.class);
|
||||
List<Predicate> 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<Book> query = em.createQuery(cq);
|
||||
return query.getResultList();
|
||||
}
|
||||
|
||||
}
|
||||
-25
@@ -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<Book> query(String author, String title) {
|
||||
return bookRepository.findAll(where(hasAuthor(author)).and(titleContains(title)));
|
||||
}
|
||||
|
||||
}
|
||||
-16
@@ -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<Book> hasAuthor(String author) {
|
||||
return (book, cq, cb) -> cb.equal(book.get("author"), author);
|
||||
}
|
||||
|
||||
public static Specification<Book> titleContains(String title) {
|
||||
return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%");
|
||||
}
|
||||
|
||||
}
|
||||
+8
@@ -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<Bar> {
|
||||
//
|
||||
}
|
||||
+10
@@ -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<Bar, Serializable> {
|
||||
//
|
||||
}
|
||||
+8
@@ -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<Bar> {
|
||||
//
|
||||
}
|
||||
+8
@@ -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<Child> {
|
||||
//
|
||||
}
|
||||
+8
@@ -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<Foo> {
|
||||
//
|
||||
}
|
||||
+8
@@ -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<Foo> {
|
||||
//
|
||||
}
|
||||
+8
@@ -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<Parent> {
|
||||
//
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
public abstract class AbstractDao<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
protected Class<T> clazz;
|
||||
|
||||
protected final void setClazz(final Class<T> clazzToSet) {
|
||||
clazz = Preconditions.checkNotNull(clazzToSet);
|
||||
}
|
||||
}
|
||||
+37
@@ -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<T extends Serializable> extends AbstractHibernateDao<T> implements IAuditOperations<T> {
|
||||
|
||||
@Override
|
||||
public List<T> getEntitiesAtRevision(final Number revision) {
|
||||
final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession());
|
||||
final AuditQuery query = auditReader.createQuery().forEntitiesAtRevision(clazz, revision);
|
||||
final List<T> resultList = query.getResultList();
|
||||
return resultList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> getEntitiesModifiedAtRevision(final Number revision) {
|
||||
final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession());
|
||||
final AuditQuery query = auditReader.createQuery().forEntitiesModifiedAtRevision(clazz, revision);
|
||||
final List<T> resultList = query.getResultList();
|
||||
return resultList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> getRevisions() {
|
||||
final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession());
|
||||
final AuditQuery query = auditReader.createQuery().forRevisionsOfEntity(clazz, true, true);
|
||||
final List<T> resultList = query.getResultList();
|
||||
return resultList;
|
||||
}
|
||||
|
||||
}
|
||||
+59
@@ -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<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
||||
|
||||
@Autowired
|
||||
protected SessionFactory sessionFactory;
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public T findOne(final long id) {
|
||||
return (T) getCurrentSession().get(clazz, id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> 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();
|
||||
}
|
||||
|
||||
}
|
||||
+56
@@ -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<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
||||
|
||||
@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<T> findAll() {
|
||||
final CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
final CriteriaQuery<T> cq = cb.createQuery(clazz);
|
||||
final Root<T> rootEntry = cq.from(clazz);
|
||||
final CriteriaQuery<T> all = cq.select(rootEntry);
|
||||
final TypedQuery<T> 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));
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -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<T extends Serializable> extends AbstractHibernateDao<T> implements IGenericDao<T> {
|
||||
//
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
public interface IAuditOperations<T extends Serializable> {
|
||||
|
||||
List<T> getEntitiesAtRevision(Number revision);
|
||||
|
||||
List<T> getEntitiesModifiedAtRevision(Number revision);
|
||||
|
||||
List<T> getRevisions();
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public interface IGenericDao<T extends Serializable> extends IOperations<T> {
|
||||
//
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
public interface IOperations<T extends Serializable> {
|
||||
|
||||
T findOne(final long id);
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
void create(final T entity);
|
||||
|
||||
T update(final T entity);
|
||||
|
||||
void delete(final T entity);
|
||||
|
||||
void deleteById(final long entityId);
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user