Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-8844
This commit is contained in:
@@ -7,6 +7,5 @@
|
||||
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
|
||||
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
|
||||
- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
|
||||
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
|
||||
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
|
||||
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Relevant Articles
|
||||
|
||||
* [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
|
||||
- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
|
||||
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.jpa.model;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.NamedStoredProcedureQueries;
|
||||
import javax.persistence.NamedStoredProcedureQuery;
|
||||
import javax.persistence.ParameterMode;
|
||||
import javax.persistence.StoredProcedureParameter;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "CAR")
|
||||
@NamedStoredProcedureQueries({
|
||||
@NamedStoredProcedureQuery(name = "findByYearProcedure", procedureName = "FIND_CAR_BY_YEAR", resultClasses = { Car.class }, parameters = { @StoredProcedureParameter(name = "p_year", type = Integer.class, mode = ParameterMode.IN) }) })
|
||||
public class Car {
|
||||
|
||||
private long id;
|
||||
private String model;
|
||||
private Integer year;
|
||||
|
||||
public Car(final String model, final Integer year) {
|
||||
this.model = model;
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public Car() {
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "ID", unique = true, nullable = false, scale = 0)
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "MODEL")
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(final String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
@Column(name = "YEAR")
|
||||
public Integer getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(final Integer year) {
|
||||
this.year = year;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.jpa.model;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class QueryParameter {
|
||||
|
||||
private Map<String, Object> parameters = null;
|
||||
|
||||
private QueryParameter(final String name, final Object value) {
|
||||
this.parameters = new HashMap<>();
|
||||
this.parameters.put(name, value);
|
||||
}
|
||||
|
||||
public static QueryParameter with(final String name, final Object value) {
|
||||
return new QueryParameter(name, value);
|
||||
}
|
||||
|
||||
public QueryParameter and(final String name, final Object value) {
|
||||
this.parameters.put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Map<String, Object> parameters() {
|
||||
return this.parameters;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -20,4 +20,18 @@
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung" />
|
||||
<property name="javax.persistence.jdbc.user" value="baeldung" />
|
||||
<property name="javax.persistence.jdbc.password" value="YourPassword" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
|
||||
<property name="hibernate.show_sql" value="true" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
DELIMITER $$
|
||||
CREATE DEFINER=`root`@`localhost` PROCEDURE `FIND_CAR_BY_YEAR`(in p_year int)
|
||||
begin
|
||||
SELECT ID, MODEL, YEAR
|
||||
FROM CAR
|
||||
WHERE YEAR = p_year;
|
||||
end$$
|
||||
DELIMITER ;
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE `car` (
|
||||
`ID` int(10) NOT NULL AUTO_INCREMENT,
|
||||
`MODEL` varchar(50) NOT NULL,
|
||||
`YEAR` int(4) NOT NULL,
|
||||
PRIMARY KEY (`ID`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
|
||||
@@ -0,0 +1,5 @@
|
||||
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('123456', 'Camaro', '2012');
|
||||
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('12112', 'Fiat Panda', '2000');
|
||||
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('111000', 'Fiat Punto', '2007');
|
||||
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('3382', 'Citroen C3', '2009');
|
||||
commit;
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.jpa.storedprocedure;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.persistence.ParameterMode;
|
||||
import javax.persistence.Persistence;
|
||||
import javax.persistence.StoredProcedureQuery;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jpa.model.Car;
|
||||
|
||||
public class StoredProcedureLiveTest {
|
||||
|
||||
private static EntityManagerFactory factory = null;
|
||||
private static EntityManager entityManager = null;
|
||||
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
factory = Persistence.createEntityManagerFactory("jpa-db");
|
||||
entityManager = factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createCarTest() {
|
||||
final EntityTransaction transaction = entityManager.getTransaction();
|
||||
try {
|
||||
transaction.begin();
|
||||
final Car car = new Car("Fiat Marea", 2015);
|
||||
entityManager.persist(car);
|
||||
transaction.commit();
|
||||
} catch (final Exception e) {
|
||||
System.out.println(e.getCause());
|
||||
if (transaction.isActive()) {
|
||||
transaction.rollback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findCarsByYearNamedProcedure() {
|
||||
final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure");
|
||||
final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015);
|
||||
storedProcedure.getResultList()
|
||||
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findCarsByYearNoNamed() {
|
||||
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
|
||||
.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
|
||||
.setParameter(1, 2015);
|
||||
storedProcedure.getResultList()
|
||||
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void destroy() {
|
||||
|
||||
if (entityManager != null) {
|
||||
entityManager.close();
|
||||
}
|
||||
if (factory != null) {
|
||||
factory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence 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"
|
||||
version="2.1">
|
||||
|
||||
<persistence-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung" />
|
||||
<property name="javax.persistence.jdbc.user" value="baeldung" />
|
||||
<property name="javax.persistence.jdbc.password" value="YourPassword" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
|
||||
<property name="hibernate.show_sql" value="true" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
|
||||
@@ -9,20 +9,15 @@
|
||||
- [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)
|
||||
- [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source)
|
||||
- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
|
||||
- [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
|
||||
- [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types)
|
||||
- [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys)
|
||||
- [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
|
||||
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
|
||||
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
|
||||
|
||||
### Eclipse Config
|
||||
After importing the project into Eclipse, you may see the following error:
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
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);
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package org.baeldung.extended.persistence.dao;
|
||||
|
||||
import org.baeldung.inmemory.persistence.model.Student;
|
||||
|
||||
public interface ExtendedStudentRepository extends ExtendedRepository<Student, Long> {
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package org.baeldung.persistence.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
private String name;
|
||||
private Integer status;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name, Integer status) {
|
||||
this.name = name;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
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> {
|
||||
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
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> {
|
||||
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
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> {
|
||||
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
+1
-5
@@ -1,10 +1,6 @@
|
||||
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;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(schema = "spring_jpa_user")
|
||||
|
||||
+1
-8
@@ -1,15 +1,8 @@
|
||||
package org.baeldung.persistence.multiple.model.user;
|
||||
|
||||
import javax.persistence.*;
|
||||
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 {
|
||||
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package org.baeldung.persistence.repository;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@Repository("userRepository")
|
||||
public interface UserRepository extends JpaRepository<User, Integer> {
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = 1")
|
||||
Collection<User> findAllActiveUsers();
|
||||
|
||||
@Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true)
|
||||
Collection<User> findAllActiveUsersNative();
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1")
|
||||
User findUserByStatus(Integer status);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
|
||||
User findUserByStatusNative(Integer status);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
|
||||
User findUserByStatusAndName(Integer status, String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
|
||||
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like ?1%")
|
||||
User findUserByNameLike(String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like :name%")
|
||||
User findUserByNameLikeNamedParam(@Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
|
||||
User findUserByNameLikeNative(String name);
|
||||
|
||||
@Query(value = "SELECT u FROM User u")
|
||||
List<User> findAllUsers(Sort sort);
|
||||
|
||||
@Query(value = "SELECT u FROM User u ORDER BY id")
|
||||
Page<User> findAllUsersWithPagination(Pageable pageable);
|
||||
|
||||
@Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
|
||||
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
|
||||
|
||||
@Modifying
|
||||
@Query("update User u set u.status = :status where u.name = :name")
|
||||
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Modifying
|
||||
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNative(Integer status, String name);
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_USER
|
||||
product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_PRODUCT
|
||||
jdbc.user=sa
|
||||
jdbc.pass=
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=false
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.cache.use_second_level_cache=false
|
||||
hibernate.cache.use_query_cache=false
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
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.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { StudentJPAH2Config.class })
|
||||
@DirtiesContext
|
||||
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);
|
||||
}
|
||||
}
|
||||
-321
@@ -1,321 +0,0 @@
|
||||
package org.baeldung.persistence.repository;
|
||||
|
||||
import org.baeldung.config.PersistenceJPAConfigL2Cache;
|
||||
import org.baeldung.persistence.model.User;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.JpaSort;
|
||||
import org.springframework.data.mapping.PropertyReferenceException;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = PersistenceJPAConfigL2Cache.class)
|
||||
@DirtiesContext
|
||||
public class UserRepositoryIntegrationTest {
|
||||
|
||||
private final String USER_NAME_ADAM = "Adam";
|
||||
private final String USER_NAME_PETER = "Peter";
|
||||
private final Integer INACTIVE_STATUS = 0;
|
||||
private final Integer ACTIVE_STATUS = 1;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setStatus(INACTIVE_STATUS);
|
||||
userRepository.save(user3);
|
||||
|
||||
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
|
||||
|
||||
assertThat(allActiveUsers.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setStatus(INACTIVE_STATUS);
|
||||
userRepository.save(user3);
|
||||
|
||||
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
|
||||
|
||||
assertThat(allActiveUsers.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLike("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
|
||||
|
||||
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
|
||||
|
||||
assertThat(usersSortByName
|
||||
.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test(expected = PropertyReferenceException.class)
|
||||
public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
|
||||
|
||||
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
|
||||
|
||||
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
|
||||
|
||||
assertThat(usersSortByNameLength
|
||||
.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
|
||||
|
||||
userRepository.findAllUsers(new Sort("name"));
|
||||
|
||||
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
|
||||
|
||||
assertThat(usersSortByNameLength
|
||||
.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE2", INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", INACTIVE_STATUS));
|
||||
|
||||
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
|
||||
|
||||
assertThat(usersPage
|
||||
.getContent()
|
||||
.get(0)
|
||||
.getName()).isEqualTo("SAMPLE1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE2", INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", INACTIVE_STATUS));
|
||||
|
||||
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
|
||||
|
||||
assertThat(usersSortByNameLength
|
||||
.getContent()
|
||||
.get(0)
|
||||
.getName()).isEqualTo("SAMPLE1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() {
|
||||
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", ACTIVE_STATUS));
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
|
||||
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", ACTIVE_STATUS));
|
||||
userRepository.flush();
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanUp() {
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
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.annotation.DirtiesContext;
|
||||
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
|
||||
@DirtiesContext
|
||||
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()));
|
||||
}
|
||||
|
||||
}
|
||||
-1
@@ -8,7 +8,6 @@ import org.junit.runners.Suite;
|
||||
FooPaginationPersistenceIntegrationTest.class
|
||||
,FooServicePersistenceIntegrationTest.class
|
||||
,FooServiceSortingIntegrationTest.class
|
||||
,JpaMultipleDBIntegrationTest.class
|
||||
,FooServiceSortingWitNullsManualIntegrationTest.class
|
||||
}) // @formatter:on
|
||||
public class PersistenceTestSuite {
|
||||
|
||||
Reference in New Issue
Block a user