move spring-jpa to persistence-modules (#3134)

* move security content from spring-security-rest-full

* swagger update

* move query language to new module

* rename spring-security-rest-full to spring-rest-full

* group persistence modules

* group testing modules

* try fix conflict

* cleanup

* group and cleanup

* add readme to grouping modules

* move spring-jpa to persistence-modules
This commit is contained in:
Doha2012
2017-11-26 09:40:54 +02:00
committed by Grzegorz Piwowarek
parent aa46858c0f
commit c1ecbf5710
70 changed files with 2 additions and 1 deletions

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -0,0 +1,27 @@
=========
## Spring JPA Example Project
### Relevant Articles:
- [Spring 3 and JPA with Hibernate](http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/)
- [Transactions with Spring 3 and JPA](http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/)
- [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa)
- [JPA Pagination](http://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](http://www.baeldung.com/jpa-sort)
- [Spring JPA Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate)
- [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database)
- [Spring Data JPA Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"
This can be ignored:
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
Or:
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator

View File

@@ -0,0 +1,203 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-jpa</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-jpa</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>${xml-apis.version}</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${javax.servlet.jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
<version>${javax.servlet.servlet-api.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-jpa</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.3.8.RELEASE</org.springframework.version>
<javassist.version>3.21.0-GA</javassist.version>
<!-- persistence -->
<hibernate.version>5.2.10.Final</hibernate.version>
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
<spring-data-jpa.version>1.11.3.RELEASE</spring-data-jpa.version>
<h2.version>1.4.195</h2.version>
<!-- web -->
<javax.servlet.jstl.version>1.2</javax.servlet.jstl.version>
<javax.servlet.servlet-api.version>2.5</javax.servlet.servlet-api.version>
<!-- various -->
<hibernate-validator.version>5.4.1.Final</hibernate-validator.version>
<xml-apis.version>1.4.01</xml-apis.version>
<javax.el-api.version>2.2.5</javax.el-api.version>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.8.0</assertj.version>
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
</properties>
</project>

View File

@@ -0,0 +1,72 @@
package org.baeldung.config;
import java.util.Properties;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jndi.JndiTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-jndi.properties" })
@ComponentScan({ "org.baeldung.persistence" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJNDIConfig {
@Autowired
private Environment env;
public PersistenceJNDIConfig() {
super();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() throws NamingException {
return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url"));
}
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false");
return hibernateProperties;
}
}

View File

@@ -0,0 +1,87 @@
package org.baeldung.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "org.baeldung.persistence" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJPAConfig {
@Autowired
private Environment env;
public PersistenceJPAConfig() {
super();
}
// beans
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
}

View File

@@ -0,0 +1,89 @@
package org.baeldung.config;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "org.baeldung.persistence" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJPAConfigL2Cache {
@Autowired
private Environment env;
public PersistenceJPAConfigL2Cache() {
super();
}
// beans
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(getPackagesToScan());
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
protected String[] getPackagesToScan() {
return new String[] { "org.baeldung.persistence.model" };
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return hibernateProperties;
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
// @Configuration
@EnableTransactionManagement
@ComponentScan({ "org.baeldung.persistence" })
@ImportResource({ "classpath:jpaConfig.xml" })
public class PersistenceJPAConfigXml {
public PersistenceJPAConfigXml() {
super();
}
}

View File

@@ -0,0 +1,68 @@
package org.baeldung.config;
import java.util.HashMap;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import com.google.common.base.Preconditions;
@Configuration
@PropertySource({ "classpath:persistence-multiple-db.properties" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
public class ProductConfig {
@Autowired
private Environment env;
public ProductConfig() {
super();
}
//
@Bean
public LocalContainerEntityManagerFactoryBean productEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(productDataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.product" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
final HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
public DataSource productDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager productTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(productEntityManager().getObject());
return transactionManager;
}
}

View File

@@ -0,0 +1,24 @@
package org.baeldung.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
@ComponentScan({ "org.baeldung.web" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

View File

@@ -0,0 +1,69 @@
package org.baeldung.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.baeldung.extended.persistence.dao.ExtendedRepositoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = "org.baeldung.extended.persistence.dao", repositoryBaseClass = ExtendedRepositoryImpl.class)
@PropertySource("persistence-student-h2.properties")
@EnableTransactionManagement
public class StudentJPAH2Config {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
return hibernateProperties;
}
}

View File

@@ -0,0 +1,68 @@
package org.baeldung.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = "org.baeldung.inmemory.persistence.dao")
@PropertySource("persistence-student.properties")
@EnableTransactionManagement
public class StudentJpaConfig {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
return hibernateProperties;
}
}

View File

@@ -0,0 +1,72 @@
package org.baeldung.config;
import java.util.HashMap;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import com.google.common.base.Preconditions;
@Configuration
@PropertySource({ "classpath:persistence-multiple-db.properties" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
public class UserConfig {
@Autowired
private Environment env;
public UserConfig() {
super();
}
//
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean userEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(userDataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.user" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
final HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Primary
@Bean
public DataSource userDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("user.jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Primary
@Bean
public PlatformTransactionManager userTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(userEntityManager().getObject());
return transactionManager;
}
}

View File

@@ -0,0 +1,20 @@
package org.baeldung.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { PersistenceJNDIConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

View File

@@ -0,0 +1,29 @@
package org.baeldung.dsrouting;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
* Database access code for datasource routing example.
*/
public class ClientDao {
private static final String SQL_GET_CLIENT_NAME = "select name from client";
private final JdbcTemplate jdbcTemplate;
public ClientDao(DataSource datasource) {
this.jdbcTemplate = new JdbcTemplate(datasource);
}
public String getClientName() {
return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper)
.get(0);
}
private static RowMapper<String> rowMapper = (rs, rowNum) -> {
return rs.getString("name");
};
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.dsrouting;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Returns thread bound client lookup key for current context.
*/
public class ClientDataSourceRouter extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return ClientDatabaseContextHolder.getClientDatabase();
}
}

View File

@@ -0,0 +1,7 @@
package org.baeldung.dsrouting;
public enum ClientDatabase {
CLIENT_A, CLIENT_B
}

View File

@@ -0,0 +1,26 @@
package org.baeldung.dsrouting;
import org.springframework.util.Assert;
/**
* Thread shared context to point to the datasource which should be used. This
* enables context switches between different clients.
*/
public class ClientDatabaseContextHolder {
private static final ThreadLocal<ClientDatabase> CONTEXT = new ThreadLocal<>();
public static void set(ClientDatabase clientDatabase) {
Assert.notNull(clientDatabase, "clientDatabase cannot be null");
CONTEXT.set(clientDatabase);
}
public static ClientDatabase getClientDatabase() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.dsrouting;
/**
* Service layer code for datasource routing example. Here, the service methods are responsible
* for setting and clearing the context.
*/
public class ClientService {
private final ClientDao clientDao;
public ClientService(ClientDao clientDao) {
this.clientDao = clientDao;
}
public String getClientName(ClientDatabase clientDb) {
ClientDatabaseContextHolder.set(clientDb);
String clientName = this.clientDao.getClientName();
ClientDatabaseContextHolder.clear();
return clientName;
}
}

View File

@@ -0,0 +1,12 @@
package org.baeldung.extended.persistence.dao;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
@NoRepositoryBean
public interface ExtendedRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
public List<T> findByAttributeContainsText(String attributeName, String text);
}

View File

@@ -0,0 +1,36 @@
package org.baeldung.extended.persistence.dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
public class ExtendedRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements ExtendedRepository<T, ID> {
private EntityManager entityManager;
public ExtendedRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
@Transactional
public List<T> findByAttributeContainsText(String attributeName, String text) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<T> query = builder.createQuery(getDomainClass());
Root<T> root = query.from(getDomainClass());
query.select(root)
.where(builder.like(root.<String> get(attributeName), "%" + text + "%"));
TypedQuery<T> q = entityManager.createQuery(query);
return q.getResultList();
}
}

View File

@@ -0,0 +1,6 @@
package org.baeldung.extended.persistence.dao;
import org.baeldung.inmemory.persistence.model.Student;
public interface ExtendedStudentRepository extends ExtendedRepository<Student, Long> {
}

View File

@@ -0,0 +1,7 @@
package org.baeldung.inmemory.persistence.dao;
import org.baeldung.inmemory.persistence.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Long> {
}

View File

@@ -0,0 +1,38 @@
package org.baeldung.inmemory.persistence.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
@Id
private long id;
private String name;
public Student() {
}
public Student(long id, String name) {
super();
this.id = id;
this.name = 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;
}
}

View File

@@ -0,0 +1,46 @@
package org.baeldung.persistence.dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public abstract class AbstractJpaDAO<T extends Serializable> {
private Class<T> clazz;
@PersistenceContext
private EntityManager entityManager;
public final void setClazz(final Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
public T findOne(final long id) {
return entityManager.find(clazz, id);
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return entityManager.createQuery("from " + clazz.getName()).getResultList();
}
public void create(final T entity) {
entityManager.persist(entity);
}
public T update(final T entity) {
return entityManager.merge(entity);
}
public void delete(final T entity) {
entityManager.remove(entity);
}
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
delete(entity);
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooDao extends AbstractJpaDAO<Foo> implements IFooDao {
public FooDao() {
super();
setClazz(Foo.class);
}
// API
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.persistence.dao;
import java.util.List;
import org.baeldung.persistence.model.Foo;
public interface IFooDao {
Foo findOne(long id);
List<Foo> findAll();
void create(Foo entity);
Foo update(Foo entity);
void delete(Foo entity);
void deleteById(long entityId);
}

View File

@@ -0,0 +1,102 @@
package org.baeldung.persistence.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
@Entity
public class Bar implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OrderBy("name ASC")
List<Foo> fooList;
public Bar() {
super();
}
public Bar(final String name) {
super();
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<Foo> getFooList() {
return fooList;
}
public void setFooList(final List<Foo> fooList) {
this.fooList = fooList;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,92 @@
package org.baeldung.persistence.model;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
@ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER)
@JoinColumn(name = "BAR_ID")
private Bar bar;
public Bar getBar() {
return bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
public long getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((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();
}
}

View File

@@ -0,0 +1,8 @@
package org.baeldung.persistence.multiple.dao.product;
import org.baeldung.persistence.multiple.model.product.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Integer> {
}

View File

@@ -0,0 +1,8 @@
package org.baeldung.persistence.multiple.dao.user;
import org.baeldung.persistence.multiple.model.user.Possession;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PossessionRepository extends JpaRepository<Possession, Long> {
}

View File

@@ -0,0 +1,8 @@
package org.baeldung.persistence.multiple.dao.user;
import org.baeldung.persistence.multiple.model.user.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Integer> {
}

View File

@@ -0,0 +1,52 @@
package org.baeldung.persistence.multiple.model.product;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(schema = "spring_jpa_product")
public class Product {
@Id
private int id;
private String name;
private double price;
public Product() {
super();
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(final double price) {
this.price = price;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Product [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,86 @@
package org.baeldung.persistence.multiple.model.user;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(schema = "spring_jpa_user")
public class Possession {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public Possession() {
super();
}
public Possession(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + (int) (id ^ (id >>> 32));
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Possession other = (Possession) obj;
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,81 @@
package org.baeldung.persistence.multiple.model.user;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(schema = "spring_jpa_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@Column(unique = true, nullable = false)
private String email;
private int age;
@OneToMany
List<Possession> possessionList;
public User() {
super();
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,36 @@
package org.baeldung.persistence.service;
import java.util.List;
import org.baeldung.persistence.dao.IFooDao;
import org.baeldung.persistence.model.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class FooService {
@Autowired
private IFooDao dao;
public FooService() {
super();
}
// API
public void create(final Foo entity) {
dao.create(entity);
}
public Foo findOne(final long id) {
return dao.findOne(id);
}
public List<Foo> findAll() {
return dao.findAll();
}
}

View File

@@ -0,0 +1,33 @@
package org.baeldung.sqlfiles;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Country {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@Column(nullable = false)
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.web;
import org.baeldung.persistence.service.FooService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
@Autowired
private FooService fooService;
@GetMapping("/")
public String main(Model model) {
model.addAttribute("foos", fooService.findAll());
return "index";
}
}

View File

@@ -0,0 +1 @@
<ResourceLink name="jdbc/BaeldungDatabase" global="jdbc/BaeldungDatabase" type="javax.sql.DataSource"/>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,13 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
# jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

View File

@@ -0,0 +1,8 @@
# jdbc.X
jdbc.url=java:comp/env/jdbc/BaeldungDatabase
# hibernate.X
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=false
#hibernate.hbm2ddl.auto=create
hibernate.hbm2ddl.auto=update

View File

@@ -0,0 +1,13 @@
# jdbc.X
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
user.jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_user?createDatabaseIfNotExist=true
product.jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_product?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
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false

View File

@@ -0,0 +1,12 @@
# jdbc.X
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_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
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false

View File

@@ -0,0 +1,12 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
# jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false

View File

@@ -0,0 +1,11 @@
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myDb
jdbc.user=tutorialuser
jdbc.pass=tutorialpass
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:persistence-mysql.properties"/>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="org.baeldung.persistence.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<!-- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> <property name="generateDdl" value="${jpa.generateDdl}" /> <property name="databasePlatform"
value="${persistence.dialect}" /> </bean> -->
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<tx:annotation-driven/>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>

View File

@@ -0,0 +1,6 @@
<Resource name="jdbc/BaeldungDatabase" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:5432/postgres"
username="baeldung" password="pass1234" maxActive="20" maxIdle="10" maxWait="-1"/>

View File

@@ -0,0 +1 @@
spring.jpa.hibernate.ddl-auto=none

View File

@@ -0,0 +1,14 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Baeldung - Spring JNA JNDI</title>
</head>
<body>
<c:forEach var="foo" items="${foos}">
<p>
<c:out value="${foo.name}" />
</p>
</c:forEach>
</body>
</html>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="punit">
<class>org.baeldung.persistence.model.Foo</class>
<class>org.baeldung.persistence.model.Bar</class>
<properties>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/HIBERTEST"/>
<property name="javax.persistence.ddl-generation" value="drop-and-create-tables"/>
<property name="javax.persistence.logging.level" value="INFO"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
</properties>
</persistence-unit>
</persistence>

View File

@@ -0,0 +1,53 @@
package org.baeldung.dsrouting;
import static org.junit.Assert.assertEquals;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class)
public class DataSourceRoutingIntegrationTest {
@Autowired
DataSource routingDatasource;
@Autowired
ClientService clientService;
@Before
public void setup() {
final String SQL_CLIENT_A = "insert into client (id, name) values (1, 'CLIENT A')";
final String SQL_CLIENT_B = "insert into client (id, name) values (2, 'CLIENT B')";
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(routingDatasource);
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_A);
jdbcTemplate.execute(SQL_CLIENT_A);
ClientDatabaseContextHolder.clear();
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_B);
jdbcTemplate.execute(SQL_CLIENT_B);
ClientDatabaseContextHolder.clear();
}
@Test
public void givenClientDbs_whenContextsSwitch_thenRouteToCorrectDatabase() throws Exception {
// test ACME WIDGETS
String clientName = clientService.getClientName(ClientDatabase.CLIENT_A);
assertEquals(clientName, "CLIENT A");
// test WIDGETS_ARE_US
clientName = clientService.getClientName(ClientDatabase.CLIENT_B);
assertEquals(clientName, "CLIENT B");
}
}

View File

@@ -0,0 +1,51 @@
package org.baeldung.dsrouting;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
public class DataSourceRoutingTestConfiguration {
@Bean
public ClientService clientService() {
return new ClientService(new ClientDao(clientDatasource()));
}
@Bean
public DataSource clientDatasource() {
Map<Object, Object> targetDataSources = new HashMap<>();
DataSource clientADatasource = clientADatasource();
DataSource clientBDatasource = clientBDatasource();
targetDataSources.put(ClientDatabase.CLIENT_A, clientADatasource);
targetDataSources.put(ClientDatabase.CLIENT_B, clientBDatasource);
ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter();
clientRoutingDatasource.setTargetDataSources(targetDataSources);
clientRoutingDatasource.setDefaultTargetDataSource(clientADatasource);
return clientRoutingDatasource;
}
private DataSource clientADatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2)
.setName("CLIENT_A")
.addScript("classpath:dsrouting-db.sql")
.build();
}
private DataSource clientBDatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2)
.setName("CLIENT_B")
.addScript("classpath:dsrouting-db.sql")
.build();
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.persistence.deletion.config;
import org.baeldung.config.PersistenceJPAConfigL2Cache;
import java.util.Properties;
public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache {
public PersistenceJPAConfigDeletion() {
super();
}
@Override
protected String[] getPackagesToScan() {
return new String[] { "org.baeldung.persistence.deletion.model" };
}
}

View File

@@ -0,0 +1,60 @@
package org.baeldung.persistence.deletion.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "BAR")
public class Bar {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
List<Baz> bazList = new ArrayList<>();
public Bar() {
super();
}
public Bar(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<Baz> getBazList() {
return bazList;
}
public void setBazList(final List<Baz> bazList) {
this.bazList = bazList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,48 @@
package org.baeldung.persistence.deletion.model;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "BAZ")
public class Baz {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
public Baz() {
super();
}
public Baz(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,63 @@
package org.baeldung.persistence.deletion.model;
import org.hibernate.annotations.Where;
import javax.persistence.*;
@Entity
@Table(name = "FOO")
@Where(clause = "DELETED = 0")
public class Foo {
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
@Column(name = "DELETED")
private Integer deleted = 0;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "BAR_ID")
private Bar bar;
public Bar getBar() {
return bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
public long getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public void setDeleted() {
this.deleted = 1;
}
}

View File

@@ -0,0 +1,39 @@
package org.baeldung.persistence.repository;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import javax.annotation.Resource;
import org.baeldung.config.StudentJPAH2Config;
import org.baeldung.extended.persistence.dao.ExtendedStudentRepository;
import org.baeldung.inmemory.persistence.model.Student;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { StudentJPAH2Config.class})
public class ExtendedStudentRepositoryIntegrationTest {
@Resource
private ExtendedStudentRepository extendedStudentRepository;
@Before
public void setup(){
Student student = new Student(1, "john");
extendedStudentRepository.save(student);
Student student2 = new Student(2, "johnson");
extendedStudentRepository.save(student2);
Student student3 = new Student(3, "tom");
extendedStudentRepository.save(student3);
}
@Test
public void givenStudents_whenFindByName_thenGetOk(){
List<Student> students = extendedStudentRepository.findByAttributeContainsText("name", "john");
assertThat(students.size()).isEqualTo(2);
}
}

View File

@@ -0,0 +1,37 @@
package org.baeldung.persistence.repository;
import org.baeldung.config.StudentJpaConfig;
import org.baeldung.inmemory.persistence.dao.StudentRepository;
import org.baeldung.inmemory.persistence.model.Student;
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 org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional
public class InMemoryDBIntegrationTest {
@Resource
private StudentRepository studentRepository;
private static final long ID = 1;
private static final String NAME="john";
@Test
public void givenStudent_whenSave_thenGetOk(){
Student student = new Student(ID, NAME);
studentRepository.save(student);
Student student2 = studentRepository.findOne(ID);
assertEquals("name incorrect", NAME, student2.getName());
}
}

View File

@@ -0,0 +1,159 @@
package org.baeldung.persistence.service;
import org.baeldung.persistence.deletion.config.PersistenceJPAConfigDeletion;
import org.baeldung.persistence.deletion.model.Bar;
import org.baeldung.persistence.deletion.model.Baz;
import org.baeldung.persistence.deletion.model.Foo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfigDeletion.class }, loader = AnnotationConfigContextLoader.class)
public class DeletionIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private PlatformTransactionManager platformTransactionManager;
@Before
public final void before() {
entityManager.getEntityManagerFactory().getCache().evictAll();
}
@Test
@Transactional
public final void givenEntityIsRemoved_thenItIsNotInDB() {
Foo foo = new Foo("foo");
entityManager.persist(foo);
flushAndClear();
foo = entityManager.find(Foo.class, foo.getId());
assertThat(foo, notNullValue());
entityManager.remove(foo);
flushAndClear();
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
}
@Test
@Transactional
public final void givenEntityIsRemovedAndReferencedByAnotherEntity_thenItIsNotRemoved() {
Bar bar = new Bar("bar");
Foo foo = new Foo("foo");
foo.setBar(bar);
entityManager.persist(foo);
flushAndClear();
foo = entityManager.find(Foo.class, foo.getId());
bar = entityManager.find(Bar.class, bar.getId());
entityManager.remove(bar);
flushAndClear();
bar = entityManager.find(Bar.class, bar.getId());
assertThat(bar, notNullValue());
foo = entityManager.find(Foo.class, foo.getId());
foo.setBar(null);
entityManager.remove(bar);
flushAndClear();
assertThat(entityManager.find(Bar.class, bar.getId()), nullValue());
}
@Test
@Transactional
public final void givenEntityIsRemoved_thenRemovalIsCascaded() {
Bar bar = new Bar("bar");
Foo foo = new Foo("foo");
foo.setBar(bar);
entityManager.persist(foo);
flushAndClear();
foo = entityManager.find(Foo.class, foo.getId());
entityManager.remove(foo);
flushAndClear();
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
assertThat(entityManager.find(Bar.class, bar.getId()), nullValue());
}
@Test
@Transactional
public final void givenEntityIsDisassociated_thenOrphanRemovalIsApplied() {
Bar bar = new Bar("bar");
Baz baz = new Baz("baz");
bar.getBazList().add(baz);
entityManager.persist(bar);
flushAndClear();
bar = entityManager.find(Bar.class, bar.getId());
baz = bar.getBazList().get(0);
bar.getBazList().remove(baz);
flushAndClear();
assertThat(entityManager.find(Baz.class, baz.getId()), nullValue());
}
@Test
@Transactional
public final void givenEntityIsDeletedWithJpaBulkDeleteStatement_thenItIsNotInDB() {
Foo foo = new Foo("foo");
entityManager.persist(foo);
flushAndClear();
entityManager.createQuery("delete from Foo where id = :id")
.setParameter("id", foo.getId())
.executeUpdate();
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
}
@Test
@Transactional
public final void givenEntityIsDeletedWithNativeQuery_thenItIsNotInDB() {
Foo foo = new Foo("foo");
entityManager.persist(foo);
flushAndClear();
entityManager.createNativeQuery("delete from FOO where ID = :id")
.setParameter("id", foo.getId())
.executeUpdate();
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
}
@Test
@Transactional
public final void givenEntityIsSoftDeleted_thenItIsNotReturnedFromQueries() {
Foo foo = new Foo("foo");
entityManager.persist(foo);
flushAndClear();
foo = entityManager.find(Foo.class, foo.getId());
foo.setDeleted();
flushAndClear();
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
}
private void flushAndClear() {
entityManager.flush();
entityManager.clear();
}
}

View File

@@ -0,0 +1,155 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooPaginationPersistenceIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private FooService fooService;
@Before
public final void before() {
final int minimalNumberOfEntities = 25;
if (fooService.findAll().size() <= minimalNumberOfEntities) {
for (int i = 0; i < minimalNumberOfEntities; i++) {
fooService.create(new Foo(randomAlphabetic(6)));
}
}
}
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingFirstPage_thenCorrect() {
final int pageSize = 10;
final Query query = entityManager.createQuery("From Foo");
configurePagination(query, 1, pageSize);
// When
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingLastPage_thenCorrect() {
final int pageSize = 10;
final Query queryTotal = entityManager.createQuery("Select count(f.id) from Foo f");
final long countResult = (long) queryTotal.getSingleResult();
final Query query = entityManager.createQuery("Select f from Foo as f order by f.id");
final int lastPage = (int) ((countResult / pageSize) + 1);
configurePagination(query, lastPage, pageSize);
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(lessThan(pageSize + 1)));
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() {
final int pageSize = 10;
final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name");
final List<Integer> fooIds = queryIds.getResultList();
final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids");
query.setParameter("ids", fooIds.subList(0, pageSize));
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@Test
public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() {
final int pageSize = 10;
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
typedQuery.setFirstResult(0);
typedQuery.setMaxResults(pageSize);
final List<Foo> fooList = typedQuery.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@Test
public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions() {
int pageNumber = 1;
final int pageSize = 10;
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class)));
final Long count = entityManager.createQuery(countQuery).getSingleResult();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
TypedQuery<Foo> typedQuery;
while (pageNumber < count.intValue()) {
typedQuery = entityManager.createQuery(select);
typedQuery.setFirstResult(pageNumber - 1);
typedQuery.setMaxResults(pageSize);
System.out.println("Current page: " + typedQuery.getResultList());
pageNumber += pageSize;
}
}
// UTIL
final int determineLastPage(final int pageSize, final long countResult) {
return (int) (countResult / pageSize) + 1;
}
final void configurePagination(final Query query, final int pageNumber, final int pageSize) {
query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize);
}
}

View File

@@ -0,0 +1,67 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooServicePersistenceIntegrationTest {
@Autowired
private FooService service;
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@Test
public final void whenEntityIsCreated_thenNoExceptions() {
service.create(new Foo(randomAlphabetic(6)));
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenEntityWithLongNameIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test(expected = InvalidDataAccessApiUsageException.class)
public final void whenSameEntityIsCreatedTwice_thenDataException() {
final Foo entity = new Foo(randomAlphabetic(8));
service.create(entity);
service.create(entity);
}
@Test(expected = DataAccessException.class)
public final void temp_whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test
public final void whenEntityIsCreated_thenFound() {
final Foo fooEntity = new Foo("abc");
service.create(fooEntity);
final Foo found = service.findOne(fooEntity.getId());
Assert.assertNotNull(found);
}
}

View File

@@ -0,0 +1,116 @@
package org.baeldung.persistence.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Bar;
import org.baeldung.persistence.model.Foo;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@SuppressWarnings("unchecked")
public class FooServiceSortingIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
// tests
@Test
public final void whenSortingByOneAttributeDefaultOrder_thenPrintSortedResult() {
final String jql = "Select f from Foo as f order by f.id";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingByOneAttributeSetOrder_thenSortedPrintResult() {
final String jql = "Select f from Foo as f order by f.id desc";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingByTwoAttributes_thenPrintSortedResult() {
final String jql = "Select f from Foo as f order by f.name asc, f.id desc";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingFooByBar_thenBarsSorted() {
final String jql = "Select f from Foo as f order by f.name, f.bar.id";
final Query barJoinQuery = entityManager.createQuery(jql);
final List<Foo> fooList = barJoinQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
if (foo.getBar() != null) {
System.out.print("-------BarId:" + foo.getBar().getId());
}
}
}
@Test
public final void whenSortinfBar_thenPrintBarsSortedWithFoos() {
final String jql = "Select b from Bar as b order by b.id";
final Query barQuery = entityManager.createQuery(jql);
final List<Bar> barList = barQuery.getResultList();
for (final Bar bar : barList) {
System.out.println("Bar Id:" + bar.getId());
for (final Foo foo : bar.getFooList()) {
System.out.println("FooName:" + foo.getName());
}
}
}
@Test
public final void whenSortingFooWithCriteria_thenPrintSortedFoos() {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
final List<Foo> fooList = typedQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId());
}
}
@Test
public final void whenSortingFooWithCriteriaAndMultipleAttributes_thenPrintSortedFoos() {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id")));
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
final List<Foo> fooList = typedQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
}

View File

@@ -0,0 +1,62 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertNull;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooServiceSortingWitNullsManualIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private FooService service;
// tests
@SuppressWarnings("unchecked")
@Test
public final void whenSortingByStringNullLast_thenLastNull() {
service.create(new Foo());
service.create(new Foo(randomAlphabetic(6)));
final String jql = "Select f from Foo as f order by f.name desc NULLS LAST";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
assertNull(fooList.get(fooList.toArray().length - 1).getName());
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
}
}
@SuppressWarnings("unchecked")
@Test
public final void whenSortingByStringNullFirst_thenFirstNull() {
service.create(new Foo());
final String jql = "Select f from Foo as f order by f.name desc NULLS FIRST";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
assertNull(fooList.get(0).getName());
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
}
}
}

View File

@@ -0,0 +1,96 @@
package org.baeldung.persistence.service;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import org.baeldung.config.ProductConfig;
import org.baeldung.config.UserConfig;
import org.baeldung.persistence.multiple.dao.product.ProductRepository;
import org.baeldung.persistence.multiple.dao.user.PossessionRepository;
import org.baeldung.persistence.multiple.dao.user.UserRepository;
import org.baeldung.persistence.multiple.model.product.Product;
import org.baeldung.persistence.multiple.model.user.Possession;
import org.baeldung.persistence.multiple.model.user.User;
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.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { UserConfig.class, ProductConfig.class })
@EnableTransactionManagement
public class JpaMultipleDBIntegrationTest {
@Autowired
private UserRepository userRepository;
@Autowired
private PossessionRepository possessionRepository;
@Autowired
private ProductRepository productRepository;
// tests
@Test
@Transactional("userTransactionManager")
public void whenCreatingUser_thenCreated() {
User user = new User();
user.setName("John");
user.setEmail("john@test.com");
user.setAge(20);
Possession p = new Possession("sample");
p = possessionRepository.save(p);
user.setPossessionList(Arrays.asList(p));
user = userRepository.save(user);
final User result = userRepository.findOne(user.getId());
assertNotNull(result);
System.out.println(result.getPossessionList());
assertTrue(result.getPossessionList().size() == 1);
}
@Test
@Transactional("userTransactionManager")
public void whenCreatingUsersWithSameEmail_thenRollback() {
User user1 = new User();
user1.setName("John");
user1.setEmail("john@test.com");
user1.setAge(20);
user1 = userRepository.save(user1);
assertNotNull(userRepository.findOne(user1.getId()));
User user2 = new User();
user2.setName("Tom");
user2.setEmail("john@test.com");
user2.setAge(10);
try {
user2 = userRepository.save(user2);
userRepository.flush();
fail("DataIntegrityViolationException should be thrown!");
} catch (final DataIntegrityViolationException e) {
// Expected
} catch (final Exception e) {
fail("DataIntegrityViolationException should be thrown, instead got: " + e);
}
}
@Test
@Transactional("productTransactionManager")
public void whenCreatingProduct_thenCreated() {
Product product = new Product();
product.setName("Book");
product.setId(2);
product.setPrice(20);
product = productRepository.save(product);
assertNotNull(productRepository.findOne(product.getId()));
}
}

View File

@@ -0,0 +1,16 @@
package org.baeldung.persistence.service;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ // @formatter:off
FooPaginationPersistenceIntegrationTest.class
,FooServicePersistenceIntegrationTest.class
,FooServiceSortingIntegrationTest.class
,JpaMultipleDBIntegrationTest.class
,FooServiceSortingWitNullsManualIntegrationTest.class
}) // @formatter:on
public class PersistenceTestSuite {
//
}

View File

@@ -0,0 +1,79 @@
package org.baeldung.persistence.service;
import net.sf.ehcache.CacheManager;
import org.baeldung.config.PersistenceJPAConfigL2Cache;
import org.baeldung.persistence.model.Bar;
import org.baeldung.persistence.model.Foo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
public class SecondLevelCacheIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private FooService fooService;
@Autowired
private PlatformTransactionManager platformTransactionManager;
@Before
public final void before() {
entityManager.getEntityManagerFactory().getCache().evictAll();
}
@Test
public final void givenEntityIsLoaded_thenItIsCached() {
final Foo foo = new Foo(randomAlphabetic(6));
fooService.create(foo);
fooService.findOne(foo.getId());
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize();
assertThat(size, greaterThan(0));
}
@Test
public final void givenBarIsUpdatedInNativeQuery_thenFoosAreNotEvicted() {
final Foo foo = new Foo(randomAlphabetic(6));
fooService.create(foo);
fooService.findOne(foo.getId());
new TransactionTemplate(platformTransactionManager).execute(status -> {
final Bar bar = new Bar(randomAlphabetic(6));
entityManager.persist(bar);
final Query nativeQuery = entityManager.createNativeQuery("update BAR set NAME = :updatedName where ID = :id");
nativeQuery.setParameter("updatedName", "newName");
nativeQuery.setParameter("id", bar.getId());
nativeQuery.unwrap(org.hibernate.SQLQuery.class).addSynchronizedEntityClass(Bar.class);
return nativeQuery.executeUpdate();
});
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize();
assertThat(size, greaterThan(0));
}
@Test
public final void givenCacheableQueryIsExecuted_thenItIsCached() {
new TransactionTemplate(platformTransactionManager).execute(status -> {
return entityManager.createQuery("select f from Foo f").setHint("org.hibernate.cacheable", true).getResultList();
});
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.hibernate.cache.internal.StandardQueryCache").getSize();
assertThat(size, greaterThan(0));
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -0,0 +1,5 @@
create table client (
id numeric,
name varchar(50),
constraint pk_client primary key (id)
);

View File

@@ -0,0 +1,9 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false