[BAEL-9538] - Move persistence-related modules into the persistence folder
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
|
||||
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class)
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import com.baeldung.services.IBarService;
|
||||
import com.baeldung.services.impl.BarSpringDataJpaService;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
|
||||
import com.baeldung.services.IFooService;
|
||||
import com.baeldung.services.impl.FooService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.JpaVendorAdapter;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan({"com.baeldung.dao", "com.baeldung.services"})
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class)
|
||||
@EnableJpaAuditing
|
||||
@PropertySource("classpath:persistence.properties")
|
||||
public class PersistenceConfiguration {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceConfiguration() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
||||
emf.setDataSource(dataSource());
|
||||
emf.setPackagesToScan("com.baeldung.domain");
|
||||
|
||||
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
emf.setJpaVendorAdapter(vendorAdapter);
|
||||
emf.setJpaProperties(hibernateProperties());
|
||||
|
||||
return emf;
|
||||
}
|
||||
|
||||
@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 JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IBarService barSpringDataJpaService() {
|
||||
return new BarSpringDataJpaService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IFooService fooService() {
|
||||
return new FooService();
|
||||
}
|
||||
|
||||
private final Properties hibernateProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
|
||||
hibernateProperties.setProperty("hibernate.show_sql", "true");
|
||||
// hibernateProperties.setProperty("hibernate.format_sql", "true");
|
||||
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
|
||||
|
||||
// Envers properties
|
||||
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.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.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 javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Configuration
|
||||
@PropertySource({"classpath:persistence-multiple-db.properties"})
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
|
||||
public class PersistenceProductConfiguration {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceProductConfiguration() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean productEntityManager() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(productDataSource());
|
||||
em.setPackagesToScan("com.baeldung.domain.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;
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.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.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 javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Configuration
|
||||
@PropertySource({"classpath:persistence-multiple-db.properties"})
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
|
||||
public class PersistenceUserConfiguration {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceUserConfiguration() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean userEntityManager() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(userDataSource());
|
||||
em.setPackagesToScan("com.baeldung.domain.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.dao;
|
||||
|
||||
import com.baeldung.domain.Foo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface IFooDao extends JpaRepository<Foo, Long> {
|
||||
|
||||
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
|
||||
Foo retrieveByName(@Param("name") String name);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.domain.Article;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
public interface ArticleRepository extends JpaRepository<Article, Integer> {
|
||||
|
||||
List<Article> findAllByPublicationDate(Date publicationDate);
|
||||
|
||||
List<Article> findAllByPublicationTimeBetween(Date publicationTimeStart,
|
||||
Date publicationTimeEnd);
|
||||
|
||||
@Query("select a from Article a where a.creationDateTime <= :creationDateTime")
|
||||
List<Article> findAllWithCreationDateTimeBefore(
|
||||
@Param("creationDateTime") Date creationDateTime);
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.domain.Item;
|
||||
|
||||
@Repository
|
||||
public interface CustomItemRepository {
|
||||
|
||||
void deleteCustom(Item entity);
|
||||
|
||||
Item findItemById(Long id);
|
||||
|
||||
void findThenDelete(Long id);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.domain.ItemType;
|
||||
|
||||
@Repository
|
||||
public interface CustomItemTypeRepository {
|
||||
|
||||
void deleteCustom(ItemType entity);
|
||||
|
||||
void findThenDelete(Long id);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
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> {
|
||||
|
||||
List<T> findByAttributeContainsText(String attributeName, String text);
|
||||
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.domain.Student;
|
||||
|
||||
public interface ExtendedStudentRepository extends ExtendedRepository<Student, Long> {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.domain.Bar;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public interface IBarCrudRepository extends CrudRepository<Bar, Serializable> {
|
||||
//
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.domain.MerchandiseEntity;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface InventoryRepository extends CrudRepository<MerchandiseEntity, Long> {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.domain.ItemType;
|
||||
|
||||
@Repository
|
||||
public interface ItemTypeRepository extends JpaRepository<ItemType, Long>, CustomItemTypeRepository, CustomItemRepository {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.domain.Location;
|
||||
|
||||
@Repository
|
||||
public interface LocationRepository extends JpaRepository<Location, Long> {
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
import com.baeldung.domain.Location;
|
||||
|
||||
@org.springframework.stereotype.Repository
|
||||
public interface ReadOnlyLocationRepository extends Repository<Location, Long> {
|
||||
|
||||
Optional<Location> findById(Long id);
|
||||
|
||||
Location save(Location location);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.domain.Store;
|
||||
|
||||
@Repository
|
||||
public interface StoreRepository extends JpaRepository<Store, Long> {
|
||||
List<Store> findStoreByLocationId(Long locationId);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.dao.repositories.impl;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.domain.Item;
|
||||
import com.baeldung.dao.repositories.CustomItemRepository;
|
||||
|
||||
@Repository
|
||||
public class CustomItemRepositoryImpl implements CustomItemRepository {
|
||||
|
||||
@Autowired
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Override
|
||||
public void deleteCustom(Item item) {
|
||||
entityManager.remove(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Item findItemById(Long id) {
|
||||
return entityManager.find(Item.class, id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void findThenDelete(Long id) {
|
||||
final Item item = entityManager.find(Item.class, id);
|
||||
entityManager.remove(item);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.dao.repositories.impl;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.domain.ItemType;
|
||||
import com.baeldung.dao.repositories.CustomItemTypeRepository;
|
||||
|
||||
@Repository
|
||||
public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(CustomItemTypeRepositoryImpl.class);
|
||||
|
||||
@Autowired
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Override
|
||||
public void deleteCustom(ItemType itemType) {
|
||||
entityManager.remove(itemType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void findThenDelete(Long id) {
|
||||
ItemType itemTypeToDelete = entityManager.find(ItemType.class, id);
|
||||
entityManager.remove(itemTypeToDelete);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.dao.repositories.impl;
|
||||
|
||||
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 com.baeldung.dao.repositories.ExtendedRepository;
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.dao.repositories.product;
|
||||
|
||||
import com.baeldung.domain.product.Product;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface ProductRepository extends JpaRepository<Product, Integer> {
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.dao.repositories.user;
|
||||
|
||||
import com.baeldung.domain.user.Possession;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface PossessionRepository extends JpaRepository<Possession, Long> {
|
||||
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.dao.repositories.user;
|
||||
|
||||
import com.baeldung.domain.user.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 java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Integer> {
|
||||
|
||||
Stream<User> findAllByName(String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = 1")
|
||||
Collection<User> findAllActiveUsers();
|
||||
|
||||
@Query(value = "SELECT * FROM USERS.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.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.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.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.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.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.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNative(Integer status, String name);
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Transient;
|
||||
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
|
||||
@Entity
|
||||
class Aggregate {
|
||||
@Transient
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
@Id
|
||||
private long id;
|
||||
|
||||
private Aggregate() {
|
||||
}
|
||||
|
||||
Aggregate(long id, ApplicationEventPublisher eventPublisher) {
|
||||
this.id = id;
|
||||
this.eventPublisher = eventPublisher;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DomainEntity [id=" + id + "]";
|
||||
}
|
||||
|
||||
void domainOperation() {
|
||||
// some business logic
|
||||
if (eventPublisher != null) {
|
||||
eventPublisher.publishEvent(new DomainEvent());
|
||||
}
|
||||
}
|
||||
|
||||
long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Transient;
|
||||
|
||||
import org.springframework.data.domain.AfterDomainEventPublication;
|
||||
import org.springframework.data.domain.DomainEvents;
|
||||
|
||||
@Entity
|
||||
public class Aggregate2 {
|
||||
@Transient
|
||||
private final Collection<DomainEvent> domainEvents;
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private long id;
|
||||
|
||||
public Aggregate2() {
|
||||
domainEvents = new ArrayList<>();
|
||||
}
|
||||
|
||||
@AfterDomainEventPublication
|
||||
public void clearEvents() {
|
||||
domainEvents.clear();
|
||||
}
|
||||
|
||||
public void domainOperation() {
|
||||
// some domain operation
|
||||
domainEvents.add(new DomainEvent());
|
||||
}
|
||||
|
||||
@DomainEvents
|
||||
public Collection<DomainEvent> events() {
|
||||
return domainEvents;
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface Aggregate2Repository extends CrudRepository<Aggregate2, Long> {
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import org.springframework.data.domain.AbstractAggregateRoot;
|
||||
|
||||
@Entity
|
||||
public class Aggregate3 extends AbstractAggregateRoot<Aggregate3> {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private long id;
|
||||
|
||||
public void domainOperation() {
|
||||
// some domain operation
|
||||
registerEvent(new DomainEvent());
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
/**
|
||||
* @author goobar
|
||||
*
|
||||
*/
|
||||
public interface Aggregate3Repository extends CrudRepository<Aggregate3, Long> {
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface AggregateRepository extends CrudRepository<Aggregate, Long> {
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
@PropertySource("classpath:/ddd.properties")
|
||||
public class DddConfig {
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
class DomainEvent {
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class DomainService {
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final AggregateRepository repository;
|
||||
|
||||
public DomainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) {
|
||||
this.repository = repository;
|
||||
this.eventPublisher = eventPublisher;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void serviceDomainOperation(long entityId) {
|
||||
repository.findById(entityId)
|
||||
.ifPresent(entity -> {
|
||||
entity.domainOperation();
|
||||
repository.save(entity);
|
||||
eventPublisher.publishEvent(new DomainEvent());
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.Date;
|
||||
|
||||
@Entity
|
||||
public class Article {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
@Temporal(TemporalType.DATE)
|
||||
private Date publicationDate;
|
||||
@Temporal(TemporalType.TIME)
|
||||
private Date publicationTime;
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private Date creationDateTime;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import org.hibernate.annotations.OrderBy;
|
||||
import org.hibernate.envers.Audited;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.springframework.data.annotation.CreatedBy;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedBy;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
|
||||
@Audited
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class Bar implements Serializable {
|
||||
|
||||
private static Logger logger = Logger.getLogger(Bar.class);
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "id")
|
||||
private int id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
@OrderBy(clause = "NAME DESC")
|
||||
// @NotAudited
|
||||
private Set<Foo> fooSet = Sets.newHashSet();
|
||||
@Column(name = "operation")
|
||||
private String operation;
|
||||
@Column(name = "timestamp")
|
||||
private long timestamp;
|
||||
@Column(name = "created_date", updatable = false, nullable = false)
|
||||
@CreatedDate
|
||||
private long createdDate;
|
||||
@Column(name = "modified_date")
|
||||
@LastModifiedDate
|
||||
private long modifiedDate;
|
||||
@Column(name = "created_by")
|
||||
@CreatedBy
|
||||
private String createdBy;
|
||||
@Column(name = "modified_by")
|
||||
@LastModifiedBy
|
||||
private String modifiedBy;
|
||||
|
||||
public Bar() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Bar(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Foo> getFooSet() {
|
||||
return fooSet;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public void setFooSet(final Set<Foo> fooSet) {
|
||||
this.fooSet = fooSet;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public OPERATION getOperation() {
|
||||
return OPERATION.parse(operation);
|
||||
}
|
||||
|
||||
public void setOperation(final String operation) {
|
||||
this.operation = operation;
|
||||
}
|
||||
|
||||
public void setOperation(final OPERATION operation) {
|
||||
this.operation = operation.getValue();
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(final long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public long getCreatedDate() {
|
||||
return createdDate;
|
||||
}
|
||||
|
||||
public void setCreatedDate(final long createdDate) {
|
||||
this.createdDate = createdDate;
|
||||
}
|
||||
|
||||
public long getModifiedDate() {
|
||||
return modifiedDate;
|
||||
}
|
||||
|
||||
public void setModifiedDate(final long modifiedDate) {
|
||||
this.modifiedDate = modifiedDate;
|
||||
}
|
||||
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
public void setCreatedBy(final String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
public String getModifiedBy() {
|
||||
return modifiedBy;
|
||||
}
|
||||
|
||||
public void setModifiedBy(final String modifiedBy) {
|
||||
this.modifiedBy = modifiedBy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Bar other = (Bar) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Bar [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@PrePersist
|
||||
public void onPrePersist() {
|
||||
logger.info("@PrePersist");
|
||||
audit(OPERATION.INSERT);
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void onPreUpdate() {
|
||||
logger.info("@PreUpdate");
|
||||
audit(OPERATION.UPDATE);
|
||||
}
|
||||
|
||||
@PreRemove
|
||||
public void onPreRemove() {
|
||||
logger.info("@PreRemove");
|
||||
audit(OPERATION.DELETE);
|
||||
}
|
||||
|
||||
private void audit(final OPERATION operation) {
|
||||
setOperation(operation);
|
||||
setTimestamp((new Date()).getTime());
|
||||
}
|
||||
|
||||
public enum OPERATION {
|
||||
INSERT, UPDATE, DELETE;
|
||||
private String value;
|
||||
|
||||
OPERATION() {
|
||||
value = toString();
|
||||
}
|
||||
|
||||
public static OPERATION parse(final String value) {
|
||||
OPERATION operation = null;
|
||||
for (final OPERATION op : OPERATION.values()) {
|
||||
if (op.getValue().equals(value)) {
|
||||
operation = op;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return operation;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import org.hibernate.envers.Audited;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)})
|
||||
@Entity
|
||||
@Audited
|
||||
// @Proxy(lazy = false)
|
||||
public class Foo implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
|
||||
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "BAR_ID")
|
||||
private Bar bar = new Bar();
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public Bar getBar() {
|
||||
return bar;
|
||||
}
|
||||
|
||||
public void setBar(final Bar bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Item {
|
||||
|
||||
private String color;
|
||||
private String grade;
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
@ManyToOne
|
||||
private ItemType itemType;
|
||||
|
||||
private String name;
|
||||
private BigDecimal price;
|
||||
@ManyToOne
|
||||
private Store store;
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public String getGrade() {
|
||||
return grade;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public ItemType getItemType() {
|
||||
return itemType;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public Store getStore() {
|
||||
return store;
|
||||
}
|
||||
|
||||
public void setColor(String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public void setGrade(String grade) {
|
||||
this.grade = grade;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setItemType(ItemType itemType) {
|
||||
this.itemType = itemType;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public void setStore(Store store) {
|
||||
this.store = store;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class ItemType {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
@OneToMany(cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "ITEM_TYPE_ID")
|
||||
private List<Item> items = new ArrayList<>();
|
||||
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<Item> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setItems(List<Item> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class KVTag {
|
||||
private String key;
|
||||
private String value;
|
||||
|
||||
public KVTag() {
|
||||
}
|
||||
|
||||
public KVTag(String key, String value) {
|
||||
super();
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class Location {
|
||||
|
||||
private String city;
|
||||
private String country;
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
@OneToMany(cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "LOCATION_ID")
|
||||
private List<Store> stores = new ArrayList<>();
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<Store> getStores() {
|
||||
return stores;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setStores(List<Store> stores) {
|
||||
this.stores = stores;
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
public class MerchandiseEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
private BigDecimal price;
|
||||
|
||||
private String brand;
|
||||
|
||||
public MerchandiseEntity() {
|
||||
}
|
||||
|
||||
public MerchandiseEntity(String title, BigDecimal price) {
|
||||
this.title = title;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
public void setBrand(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MerchandiseEntity{" +
|
||||
"id=" + id +
|
||||
", title='" + title + '\'' +
|
||||
", price=" + price +
|
||||
", brand='" + brand + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class SkillTag {
|
||||
private String name;
|
||||
private int value;
|
||||
|
||||
public SkillTag() {
|
||||
}
|
||||
|
||||
public SkillTag(String name, int value) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class Store {
|
||||
|
||||
private Boolean active;
|
||||
@Id
|
||||
private Long id;
|
||||
@OneToMany(cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "STORE_ID")
|
||||
private List<Item> items = new ArrayList<>();
|
||||
private Long itemsSold;
|
||||
|
||||
@ManyToOne
|
||||
private Location location;
|
||||
|
||||
private String name;
|
||||
|
||||
public Boolean getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<Item> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public Long getItemsSold() {
|
||||
return itemsSold;
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setActive(Boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setItems(List<Item> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public void setItemsSold(Long itemsSold) {
|
||||
this.itemsSold = itemsSold;
|
||||
}
|
||||
|
||||
public void setLocation(Location location) {
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.domain;
|
||||
|
||||
import javax.persistence.ElementCollection;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
private long id;
|
||||
private String name;
|
||||
|
||||
@ElementCollection
|
||||
private List<String> tags = new ArrayList<>();
|
||||
|
||||
@ElementCollection
|
||||
private List<SkillTag> skillTags = new ArrayList<>();
|
||||
|
||||
@ElementCollection
|
||||
private List<KVTag> kvTags = new ArrayList<>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public List<String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(List<String> tags) {
|
||||
this.tags.addAll(tags);
|
||||
}
|
||||
|
||||
public List<SkillTag> getSkillTags() {
|
||||
return skillTags;
|
||||
}
|
||||
|
||||
public void setSkillTags(List<SkillTag> skillTags) {
|
||||
this.skillTags.addAll(skillTags);
|
||||
}
|
||||
|
||||
public List<KVTag> getKVTags() {
|
||||
return this.kvTags;
|
||||
}
|
||||
|
||||
public void setKVTags(List<KVTag> kvTags) {
|
||||
this.kvTags.addAll(kvTags);
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.domain.product;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(schema = "products")
|
||||
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();
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.domain.user;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(schema = "users")
|
||||
public class Possession {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
public Possession() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Possession(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = (prime * result) + (int) (id ^ (id >>> 32));
|
||||
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final Possession other = (Possession) obj;
|
||||
if (id != other.id) {
|
||||
return false;
|
||||
}
|
||||
if (name == null) {
|
||||
if (other.name != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!name.equals(other.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.domain.user;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users", schema = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private int id;
|
||||
private String name;
|
||||
private int age;
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
private Integer status;
|
||||
@OneToMany
|
||||
List<Possession> possessionList;
|
||||
|
||||
public User() {
|
||||
super();
|
||||
}
|
||||
|
||||
public User(String name, String email, Integer status) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
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 Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import com.baeldung.domain.Bar;
|
||||
|
||||
public interface IBarService extends IOperations<Bar> {
|
||||
//
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import com.baeldung.domain.Foo;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
public interface IFooService extends IOperations<Foo> {
|
||||
|
||||
Foo retrieveByName(String name);
|
||||
|
||||
Page<Foo> findPaginated(Pageable pageable);
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
public interface IOperations<T extends Serializable> {
|
||||
|
||||
T findOne(final long id);
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
Page<T> findPaginated(int page, int size);
|
||||
|
||||
// write
|
||||
|
||||
T create(final T entity);
|
||||
|
||||
T update(final T entity);
|
||||
|
||||
void delete(final T entity);
|
||||
|
||||
void deleteById(final long entityId);
|
||||
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.services.impl;
|
||||
|
||||
import com.baeldung.services.IOperations;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Transactional
|
||||
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
// read - one
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public T findOne(final long id) {
|
||||
return getDao().findById(id).orElse(null);
|
||||
}
|
||||
|
||||
// read - all
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<T> findPaginated(final int page, final int size) {
|
||||
return getDao().findAll(new PageRequest(page, size));
|
||||
}
|
||||
|
||||
// write
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(final T entity) {
|
||||
getDao().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(final long entityId) {
|
||||
getDao().deleteById(entityId);
|
||||
}
|
||||
|
||||
protected abstract PagingAndSortingRepository<T, Long> getDao();
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.services.impl;
|
||||
|
||||
import com.baeldung.services.IOperations;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Transactional(value = "transactionManager")
|
||||
public abstract class AbstractSpringDataJpaService<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
@Override
|
||||
public T findOne(final long id) {
|
||||
return getDao().findById(id).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(final T entity) {
|
||||
getDao().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(final long entityId) {
|
||||
getDao().deleteById(entityId);
|
||||
}
|
||||
|
||||
protected abstract CrudRepository<T, Serializable> getDao();
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.services.impl;
|
||||
|
||||
import com.baeldung.domain.Bar;
|
||||
import com.baeldung.dao.repositories.IBarCrudRepository;
|
||||
import com.baeldung.services.IBarService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class BarSpringDataJpaService extends AbstractSpringDataJpaService<Bar> implements IBarService {
|
||||
|
||||
@Autowired
|
||||
private IBarCrudRepository dao;
|
||||
|
||||
public BarSpringDataJpaService() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CrudRepository<Bar, Serializable> getDao() {
|
||||
return dao;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<Bar> findPaginated(int page, int size) {
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.services.impl;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.baeldung.dao.IFooDao;
|
||||
import com.baeldung.domain.Foo;
|
||||
import com.baeldung.services.IFooService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class FooService extends AbstractService<Foo> implements IFooService {
|
||||
|
||||
@Autowired
|
||||
private IFooDao dao;
|
||||
|
||||
public FooService() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
protected PagingAndSortingRepository<Foo, Long> getDao() {
|
||||
return dao;
|
||||
}
|
||||
|
||||
// custom methods
|
||||
|
||||
@Override
|
||||
public Foo retrieveByName(final String name) {
|
||||
return dao.retrieveByName(name);
|
||||
}
|
||||
|
||||
// overridden to be secured
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<Foo> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<Foo> findPaginated(Pageable pageable) {
|
||||
return dao.findAll(pageable);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# spring.datasource.x
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=sa
|
||||
|
||||
# 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
|
||||
|
||||
spring.datasource.data=import_entities.sql
|
||||
@@ -0,0 +1 @@
|
||||
spring.datasource.initialization-mode=never
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# 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 USERS
|
||||
product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS
|
||||
jdbc.user=sa
|
||||
jdbc.pass=sa
|
||||
|
||||
# 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
|
||||
@@ -0,0 +1,16 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS
|
||||
jdbc.user=sa
|
||||
jdbc.pass=sa
|
||||
|
||||
# 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
|
||||
|
||||
# envers.X
|
||||
envers.audit_table_suffix=_audit_log
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.config.PersistenceProductConfiguration;
|
||||
import com.baeldung.config.PersistenceUserConfiguration;
|
||||
import com.baeldung.domain.Article;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class})
|
||||
public class ArticleRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ArticleRepository repository;
|
||||
|
||||
@Test
|
||||
public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned()
|
||||
throws Exception {
|
||||
List<Article> result = repository.findAllByPublicationDate(
|
||||
new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01")
|
||||
);
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertTrue(result.stream()
|
||||
.map(Article::getId)
|
||||
.allMatch(id -> Arrays.asList(1, 2).contains(id))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned()
|
||||
throws Exception {
|
||||
List<Article> result = repository.findAllByPublicationTimeBetween(
|
||||
new SimpleDateFormat("HH:mm").parse("15:15"),
|
||||
new SimpleDateFormat("HH:mm").parse("16:30")
|
||||
);
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertTrue(result.stream()
|
||||
.map(Article::getId)
|
||||
.allMatch(id -> Arrays.asList(2, 3).contains(id))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception {
|
||||
List<Article> result = repository.findAllWithCreationDateTimeBefore(
|
||||
new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00")
|
||||
);
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertTrue(result.stream()
|
||||
.map(Article::getId)
|
||||
.allMatch(id -> Arrays.asList(2, 3).contains(id))
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.domain.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.SpringRunner;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = {PersistenceConfiguration.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);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.domain.MerchandiseEntity;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class})
|
||||
public class InventoryRepositoryIntegrationTest {
|
||||
|
||||
private static final String ORIGINAL_TITLE = "Pair of Pants";
|
||||
private static final String UPDATED_TITLE = "Branded Luxury Pants";
|
||||
private static final String UPDATED_BRAND = "Armani";
|
||||
private static final String ORIGINAL_SHORTS_TITLE = "Pair of Shorts";
|
||||
|
||||
@Autowired
|
||||
private InventoryRepository repository;
|
||||
|
||||
@Test
|
||||
public void shouldCreateNewEntryInDB() {
|
||||
MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE);
|
||||
pants = repository.save(pants);
|
||||
|
||||
MerchandiseEntity shorts = new MerchandiseEntity(ORIGINAL_SHORTS_TITLE, new BigDecimal(3));
|
||||
shorts = repository.save(shorts);
|
||||
|
||||
assertNotNull(pants.getId());
|
||||
assertNotNull(shorts.getId());
|
||||
assertNotEquals(pants.getId(), shorts.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUpdateExistingEntryInDB() {
|
||||
MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE);
|
||||
pants = repository.save(pants);
|
||||
|
||||
Long originalId = pants.getId();
|
||||
|
||||
pants.setTitle(UPDATED_TITLE);
|
||||
pants.setPrice(BigDecimal.TEN);
|
||||
pants.setBrand(UPDATED_BRAND);
|
||||
|
||||
MerchandiseEntity result = repository.save(pants);
|
||||
|
||||
assertEquals(originalId, result.getId());
|
||||
assertEquals(UPDATED_TITLE, result.getTitle());
|
||||
assertEquals(BigDecimal.TEN, result.getPrice());
|
||||
assertEquals(UPDATED_BRAND, result.getBrand());
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static junit.framework.TestCase.assertFalse;
|
||||
import static junit.framework.TestCase.assertNotNull;
|
||||
import static junit.framework.TestCase.assertNull;
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.config.PersistenceProductConfiguration;
|
||||
import com.baeldung.config.PersistenceUserConfiguration;
|
||||
import com.baeldung.domain.Item;
|
||||
import com.baeldung.domain.ItemType;
|
||||
import com.baeldung.domain.Location;
|
||||
import com.baeldung.domain.Store;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(excludeAutoConfiguration = { PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class })
|
||||
public class JpaRepositoriesIntegrationTest {
|
||||
@Autowired
|
||||
private LocationRepository locationRepository;
|
||||
@Autowired
|
||||
private StoreRepository storeRepository;
|
||||
@Autowired
|
||||
private ItemTypeRepository compositeRepository;
|
||||
@Autowired
|
||||
private ReadOnlyLocationRepository readOnlyRepository;
|
||||
|
||||
@Test
|
||||
public void whenSaveLocation_ThenGetSameLocation() {
|
||||
Location location = new Location();
|
||||
location.setId(100L);
|
||||
location.setCountry("Country H");
|
||||
location.setCity("City Hundred");
|
||||
location = locationRepository.saveAndFlush(location);
|
||||
|
||||
Location otherLocation = locationRepository.getOne(location.getId());
|
||||
assertEquals("Country H", otherLocation.getCountry());
|
||||
assertEquals("City Hundred", otherLocation.getCity());
|
||||
|
||||
locationRepository.delete(otherLocation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocationId_whenFindStores_thenGetStores() {
|
||||
List<Store> stores = storeRepository.findStoreByLocationId(1L);
|
||||
assertEquals(1, stores.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenItemTypeId_whenDeleted_ThenItemTypeDeleted() {
|
||||
Optional<ItemType> itemType = compositeRepository.findById(1L);
|
||||
assertTrue(itemType.isPresent());
|
||||
compositeRepository.deleteCustom(itemType.get());
|
||||
itemType = compositeRepository.findById(1L);
|
||||
assertFalse(itemType.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenItemId_whenUsingCustomRepo_ThenDeleteAppropriateEntity() {
|
||||
Item item = compositeRepository.findItemById(1L);
|
||||
assertNotNull(item);
|
||||
compositeRepository.deleteCustom(item);
|
||||
item = compositeRepository.findItemById(1L);
|
||||
assertNull(item);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenItemAndItemType_WhenAmbiguousDeleteCalled_ThenItemTypeDeletedAndNotItem() {
|
||||
Optional<ItemType> itemType = compositeRepository.findById(1L);
|
||||
assertTrue(itemType.isPresent());
|
||||
Item item = compositeRepository.findItemById(2L);
|
||||
assertNotNull(item);
|
||||
|
||||
compositeRepository.findThenDelete(1L);
|
||||
Optional<ItemType> sameItemType = compositeRepository.findById(1L);
|
||||
assertFalse(sameItemType.isPresent());
|
||||
Item sameItem = compositeRepository.findItemById(2L);
|
||||
assertNotNull(sameItem);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingReadOnlyRepo_thenHaveOnlyReadOnlyOperationsAvailable() {
|
||||
Optional<Location> location = readOnlyRepository.findById(1L);
|
||||
assertNotNull(location);
|
||||
}
|
||||
}
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
package com.baeldung.dao.repositories;
|
||||
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.dao.repositories.user.UserRepository;
|
||||
import com.baeldung.domain.user.User;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
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.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = PersistenceConfiguration.class)
|
||||
@DirtiesContext
|
||||
public class UserRepositoryIntegrationTest {
|
||||
|
||||
private final String USER_NAME_ADAM = "Adam";
|
||||
private final String USER_NAME_PETER = "Peter";
|
||||
|
||||
private final String USER_EMAIL = "email@example.com";
|
||||
private final String USER_EMAIL2 = "email2@example.com";
|
||||
private final String USER_EMAIL3 = "email3@example.com";
|
||||
private final String USER_EMAIL4 = "email4@example.com";
|
||||
private final String USER_EMAIL5 = "email5@example.com";
|
||||
private final String USER_EMAIL6 = "email6@example.com";
|
||||
|
||||
private final Integer INACTIVE_STATUS = 0;
|
||||
private final Integer ACTIVE_STATUS = 1;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setEmail(USER_EMAIL);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setEmail(USER_EMAIL3);
|
||||
userRepository.save(user3);
|
||||
|
||||
User user4 = new User();
|
||||
user4.setName("SAMPLE");
|
||||
user4.setEmail(USER_EMAIL4);
|
||||
userRepository.save(user4);
|
||||
|
||||
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
|
||||
assertThat(foundUsersStream.count()).isEqualTo(3l);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setEmail(USER_EMAIL);
|
||||
user1.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setEmail(USER_EMAIL3);
|
||||
user3.setStatus(INACTIVE_STATUS);
|
||||
userRepository.save(user3);
|
||||
|
||||
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
|
||||
|
||||
assertThat(allActiveUsers.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setEmail(USER_EMAIL);
|
||||
user1.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setEmail(USER_EMAIL3);
|
||||
user3.setStatus(INACTIVE_STATUS);
|
||||
userRepository.save(user3);
|
||||
|
||||
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
|
||||
|
||||
assertThat(allActiveUsers.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLike("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL3, 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, USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL3, 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, USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL3, 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, USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", USER_EMAIL6, 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, USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", USER_EMAIL6, 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", USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
|
||||
userRepository.flush();
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanUp() {
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
@SpringJUnitConfig
|
||||
@SpringBootTest
|
||||
class Aggregate2EventsIntegrationTest {
|
||||
@MockBean
|
||||
private TestEventHandler eventHandler;
|
||||
@Autowired
|
||||
private Aggregate2Repository repository;
|
||||
|
||||
// @formatter:off
|
||||
@DisplayName("given aggregate with @AfterDomainEventPublication,"
|
||||
+ " when do domain operation and save twice,"
|
||||
+ " then an event is published only for the first time")
|
||||
// @formatter:on
|
||||
@Test
|
||||
void afterDomainEvents() {
|
||||
// given
|
||||
Aggregate2 aggregate = new Aggregate2();
|
||||
|
||||
// when
|
||||
aggregate.domainOperation();
|
||||
repository.save(aggregate);
|
||||
repository.save(aggregate);
|
||||
|
||||
// then
|
||||
verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class));
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void beforeEach() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
// @formatter:off
|
||||
@DisplayName("given aggregate with @DomainEvents,"
|
||||
+ " when do domain operation and save,"
|
||||
+ " then an event is published")
|
||||
// @formatter:on
|
||||
@Test
|
||||
void domainEvents() {
|
||||
// given
|
||||
Aggregate2 aggregate = new Aggregate2();
|
||||
|
||||
// when
|
||||
aggregate.domainOperation();
|
||||
repository.save(aggregate);
|
||||
|
||||
// then
|
||||
verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class));
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
@SpringJUnitConfig
|
||||
@SpringBootTest
|
||||
class Aggregate3EventsIntegrationTest {
|
||||
|
||||
@MockBean
|
||||
private TestEventHandler eventHandler;
|
||||
@Autowired
|
||||
private Aggregate3Repository repository;
|
||||
|
||||
// @formatter:off
|
||||
@DisplayName("given aggregate extending AbstractAggregateRoot,"
|
||||
+ " when do domain operation and save twice,"
|
||||
+ " then an event is published only for the first time")
|
||||
// @formatter:on
|
||||
@Test
|
||||
void afterDomainEvents() {
|
||||
// given
|
||||
Aggregate3 aggregate = new Aggregate3();
|
||||
|
||||
// when
|
||||
aggregate.domainOperation();
|
||||
repository.save(aggregate);
|
||||
repository.save(aggregate);
|
||||
|
||||
// then
|
||||
verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class));
|
||||
}
|
||||
|
||||
// @formatter:off
|
||||
@DisplayName("given aggregate extending AbstractAggregateRoot,"
|
||||
+ " when do domain operation and save,"
|
||||
+ " then an event is published")
|
||||
// @formatter:on
|
||||
@Test
|
||||
void domainEvents() {
|
||||
// given
|
||||
Aggregate3 aggregate = new Aggregate3();
|
||||
|
||||
// when
|
||||
aggregate.domainOperation();
|
||||
repository.save(aggregate);
|
||||
|
||||
// then
|
||||
verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class));
|
||||
}
|
||||
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
@SpringJUnitConfig
|
||||
@SpringBootTest
|
||||
class AggregateEventsIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private DomainService domainService;
|
||||
|
||||
@MockBean
|
||||
private TestEventHandler eventHandler;
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
@Autowired
|
||||
private AggregateRepository repository;
|
||||
|
||||
// @formatter:off
|
||||
@DisplayName("given existing aggregate,"
|
||||
+ " when do domain operation directly on aggregate,"
|
||||
+ " then domain event is NOT published")
|
||||
// @formatter:on
|
||||
@Test
|
||||
void aggregateEventsTest() {
|
||||
Aggregate existingDomainEntity = new Aggregate(0, eventPublisher);
|
||||
repository.save(existingDomainEntity);
|
||||
|
||||
// when
|
||||
repository.findById(existingDomainEntity.getId())
|
||||
.get()
|
||||
.domainOperation();
|
||||
|
||||
// then
|
||||
verifyZeroInteractions(eventHandler);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void beforeEach() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
// @formatter:off
|
||||
@DisplayName("given existing aggregate,"
|
||||
+ " when do domain operation on service,"
|
||||
+ " then domain event is published")
|
||||
// @formatter:on
|
||||
@Test
|
||||
void serviceEventsTest() {
|
||||
Aggregate existingDomainEntity = new Aggregate(1, eventPublisher);
|
||||
repository.save(existingDomainEntity);
|
||||
|
||||
// when
|
||||
domainService.serviceDomainOperation(existingDomainEntity.getId());
|
||||
|
||||
// then
|
||||
verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class));
|
||||
}
|
||||
|
||||
@TestConfiguration
|
||||
public static class TestConfig {
|
||||
@Bean
|
||||
public DomainService domainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) {
|
||||
return new DomainService(repository, eventPublisher);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.ddd.event;
|
||||
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
|
||||
interface TestEventHandler {
|
||||
@TransactionalEventListener
|
||||
void handleEvent(DomainEvent event);
|
||||
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import com.baeldung.domain.Foo;
|
||||
import com.baeldung.util.IDUtil;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public abstract class AbstractServicePersistenceIntegrationTest<T extends Serializable> {
|
||||
|
||||
// tests
|
||||
|
||||
// find - one
|
||||
|
||||
@Test
|
||||
/**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() {
|
||||
// When
|
||||
final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong());
|
||||
|
||||
// Then
|
||||
assertNull(createdResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
getApi().findOne(existingResource.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() {
|
||||
getApi().findOne(IDUtil.randomPositiveLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
final Foo retrievedResource = getApi().findOne(existingResource.getId());
|
||||
assertNotNull(retrievedResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
final Foo retrievedResource = getApi().findOne(existingResource.getId());
|
||||
assertEquals(existingResource, retrievedResource);
|
||||
}
|
||||
|
||||
// find - one - by name
|
||||
|
||||
// find - all
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenNoExceptions() {
|
||||
getApi().findAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() {
|
||||
final List<Foo> resources = getApi().findAll();
|
||||
|
||||
assertNotNull(resources);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() {
|
||||
persistNewEntity();
|
||||
|
||||
// When
|
||||
final List<Foo> allResources = getApi().findAll();
|
||||
|
||||
// Then
|
||||
assertThat(allResources, not(Matchers.<Foo> empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
final List<Foo> resources = getApi().findAll();
|
||||
|
||||
assertThat(resources, hasItem(existingResource));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() {
|
||||
persistNewEntity();
|
||||
|
||||
// When
|
||||
final List<Foo> allResources = getApi().findAll();
|
||||
|
||||
// Then
|
||||
for (final Foo resource : allResources) {
|
||||
assertNotNull(resource.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// create
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
/**/public void whenNullResourceIsCreated_thenException() {
|
||||
getApi().create(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenNoExceptions() {
|
||||
persistNewEntity();
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenResourceIsRetrievable() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
assertNotNull(getApi().findOne(existingResource.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() {
|
||||
final Foo originalResource = createNewEntity();
|
||||
final Foo savedResource = getApi().create(originalResource);
|
||||
|
||||
assertEquals(originalResource, savedResource);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenResourceWithFailedConstraintsIsCreated_thenException() {
|
||||
final Foo invalidResource = createNewEntity();
|
||||
invalidate(invalidResource);
|
||||
|
||||
getApi().create(invalidResource);
|
||||
}
|
||||
|
||||
/**
|
||||
* -- specific to the persistence engine
|
||||
*/
|
||||
@Test(expected = DataAccessException.class)
|
||||
@Ignore("Hibernate simply ignores the id silently and still saved (tracking this)")
|
||||
public void whenResourceWithIdIsCreated_thenDataAccessException() {
|
||||
final Foo resourceWithId = createNewEntity();
|
||||
resourceWithId.setId(IDUtil.randomPositiveLong());
|
||||
|
||||
getApi().create(resourceWithId);
|
||||
}
|
||||
|
||||
// update
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
/**/public void whenNullResourceIsUpdated_thenException() {
|
||||
getApi().update(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() {
|
||||
// Given
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
// When
|
||||
getApi().update(existingResource);
|
||||
}
|
||||
|
||||
/**
|
||||
* - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException
|
||||
*/
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenResourceIsUpdatedWithFailedConstraints_thenException() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
invalidate(existingResource);
|
||||
|
||||
getApi().update(existingResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() {
|
||||
// Given
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
// When
|
||||
change(existingResource);
|
||||
getApi().update(existingResource);
|
||||
|
||||
final Foo updatedResource = getApi().findOne(existingResource.getId());
|
||||
|
||||
// Then
|
||||
assertEquals(existingResource, updatedResource);
|
||||
}
|
||||
|
||||
// delete
|
||||
|
||||
// @Test(expected = RuntimeException.class)
|
||||
// public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() {
|
||||
// // When
|
||||
// getApi().delete(IDUtil.randomPositiveLong());
|
||||
// }
|
||||
//
|
||||
// @Test(expected = RuntimeException.class)
|
||||
// public void whenResourceIsDeletedByNegativeId_thenException() {
|
||||
// // When
|
||||
// getApi().delete(IDUtil.randomNegativeLong());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() {
|
||||
// // Given
|
||||
// final Foo existingResource = persistNewEntity();
|
||||
//
|
||||
// // When
|
||||
// getApi().delete(existingResource.getId());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() {
|
||||
// // Given
|
||||
// final Foo existingResource = persistNewEntity();
|
||||
//
|
||||
// // When
|
||||
// getApi().delete(existingResource.getId());
|
||||
//
|
||||
// // Then
|
||||
// assertNull(getApi().findOne(existingResource.getId()));
|
||||
// }
|
||||
|
||||
// template method
|
||||
|
||||
protected Foo createNewEntity() {
|
||||
return new Foo(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
protected abstract IOperations<Foo> getApi();
|
||||
|
||||
private final void invalidate(final Foo entity) {
|
||||
entity.setName(null);
|
||||
}
|
||||
|
||||
private final void change(final Foo entity) {
|
||||
entity.setName(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
protected Foo persistNewEntity() {
|
||||
return getApi().create(createNewEntity());
|
||||
}
|
||||
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.domain.Foo;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = {PersistenceConfiguration.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest<Foo> {
|
||||
|
||||
@Autowired
|
||||
private IFooService service;
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenContextIsBootstrapped_thenNoExceptions() {
|
||||
//
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenEntityIsCreated_thenNoExceptions() {
|
||||
service.create(new Foo(randomAlphabetic(6)));
|
||||
}
|
||||
|
||||
@Test(expected = DataIntegrityViolationException.class)
|
||||
public final void whenInvalidEntityIsCreated_thenDataException() {
|
||||
service.create(new Foo());
|
||||
}
|
||||
|
||||
@Test(expected = DataIntegrityViolationException.class)
|
||||
public final void whenEntityWithLongNameIsCreated_thenDataException() {
|
||||
service.create(new Foo(randomAlphabetic(2048)));
|
||||
}
|
||||
|
||||
// custom Query method
|
||||
|
||||
@Test
|
||||
public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() {
|
||||
final String name = randomAlphabetic(6);
|
||||
service.create(new Foo(name));
|
||||
|
||||
final Foo retrievedByName = service.retrieveByName(name);
|
||||
assertNotNull(retrievedByName);
|
||||
}
|
||||
|
||||
// work in progress
|
||||
|
||||
@Test(expected = InvalidDataAccessApiUsageException.class)
|
||||
@Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail")
|
||||
public final void whenSameEntityIsCreatedTwice_thenDataException() {
|
||||
final Foo entity = new Foo(randomAlphabetic(8));
|
||||
service.create(entity);
|
||||
service.create(entity);
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
protected final IOperations<Foo> getApi() {
|
||||
return service;
|
||||
}
|
||||
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
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.SpringRunner;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.config.PersistenceProductConfiguration;
|
||||
import com.baeldung.config.PersistenceUserConfiguration;
|
||||
import com.baeldung.dao.repositories.product.ProductRepository;
|
||||
import com.baeldung.dao.repositories.user.PossessionRepository;
|
||||
import com.baeldung.dao.repositories.user.UserRepository;
|
||||
import com.baeldung.domain.product.Product;
|
||||
import com.baeldung.domain.user.Possession;
|
||||
import com.baeldung.domain.user.User;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceUserConfiguration.class, PersistenceProductConfiguration.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(Collections.singletonList(p));
|
||||
user = userRepository.save(user);
|
||||
final Optional<User> result = userRepository.findById(user.getId());
|
||||
assertTrue(result.isPresent());
|
||||
System.out.println(result.get().getPossessionList());
|
||||
assertEquals(1, result.get().getPossessionList().size());
|
||||
}
|
||||
|
||||
@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);
|
||||
assertTrue(userRepository.findById(user1.getId()).isPresent());
|
||||
|
||||
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);
|
||||
|
||||
assertTrue(productRepository.findById(product.getId()).isPresent());
|
||||
}
|
||||
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.domain.Bar;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceConfiguration.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class SpringDataJPABarAuditIntegrationTest {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
logger.info("setUpBeforeClass()");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownAfterClass() throws Exception {
|
||||
logger.info("tearDownAfterClass()");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
@Qualifier("barSpringDataJpaService")
|
||||
private IBarService barService;
|
||||
|
||||
@Autowired
|
||||
private EntityManagerFactory entityManagerFactory;
|
||||
|
||||
private EntityManager em;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger.info("setUp()");
|
||||
em = entityManagerFactory.createEntityManager();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
logger.info("tearDown()");
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "tutorialuser")
|
||||
public final void whenBarsModified_thenBarsAudited() {
|
||||
Bar bar = new Bar("BAR1");
|
||||
barService.create(bar);
|
||||
assertEquals(bar.getCreatedDate(), bar.getModifiedDate());
|
||||
assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy());
|
||||
bar.setName("BAR2");
|
||||
bar = barService.update(bar);
|
||||
assertTrue(bar.getCreatedDate() < bar.getModifiedDate());
|
||||
assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public final class IDUtil {
|
||||
|
||||
private IDUtil() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public static String randomPositiveLongAsString() {
|
||||
return Long.toString(randomPositiveLong());
|
||||
}
|
||||
|
||||
public static String randomNegativeLongAsString() {
|
||||
return Long.toString(randomNegativeLong());
|
||||
}
|
||||
|
||||
public static long randomPositiveLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id < 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
private static long randomNegativeLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id > 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package org.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.config.PersistenceProductConfiguration;
|
||||
import com.baeldung.config.PersistenceUserConfiguration;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class})
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class SpringContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI'));
|
||||
insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI'));
|
||||
insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI'));
|
||||
|
||||
insert into location (id, country, city) values (1, 'Country X', 'City One');
|
||||
insert into location (id, country, city) values (2, 'Country X', 'City Two');
|
||||
insert into location (id, country, city) values (3, 'Country X', 'City Three');
|
||||
|
||||
insert into store (id, name, location_id, items_sold, active) values (1, 'Store One', 3, 130000, true);
|
||||
insert into store (id, name, location_id, items_sold, active) values (2, 'Store Two', 1, 170000, false);
|
||||
|
||||
insert into item_type (id, name) values (1, 'Food');
|
||||
insert into item_type (id, name) values (2, 'Furniture');
|
||||
insert into item_type (id, name) values (3, 'Electronics');
|
||||
|
||||
insert into item (id, name, store_id, item_type_id, price, grade, color) values (1, 'Food Item One', 1, 1, 100, 'A', 'Color x');
|
||||
insert into item (id, name, store_id, item_type_id, price, grade, color) values (2, 'Furniture Item One', 1, 2, 2500, 'B', 'Color y');
|
||||
insert into item (id, name, store_id, item_type_id, price, grade, color) values (3, 'Food Item Two', 1, 1, 35, 'A', 'Color z');
|
||||
insert into item (id, name, store_id, item_type_id, price, grade, color) values (5, 'Furniture Item Two', 2, 2, 1600, 'A', 'Color w');
|
||||
insert into item (id, name, store_id, item_type_id, price, grade, color) values (6, 'Food Item Three', 2, 1, 5, 'B', 'Color a');
|
||||
insert into item (id, name, store_id, item_type_id, price, grade, color) values (7, 'Electronics Item One', 2, 3, 999, 'B', 'Color b');
|
||||
Reference in New Issue
Block a user