diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java index 70ec324cb3..3e0d752bb6 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java @@ -101,7 +101,7 @@ public class OptionalChainingUnitTest { } private Optional createOptional(String input) { - if (input == null || input == "" || input == "empty") { + if (input == null || "".equals(input) || "empty".equals(input)) { return Optional.empty(); } diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md index 6d0b20135d..d75dd2208a 100644 --- a/core-kotlin-2/README.md +++ b/core-kotlin-2/README.md @@ -6,4 +6,5 @@ - [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) - [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations) - [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) -- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) \ No newline at end of file +- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) +- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations) diff --git a/persistence-modules/README.md b/persistence-modules/README.md index d5b1d2e7f4..e9a7d625cc 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -5,7 +5,6 @@ ### Relevant Articles: - [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) -- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) - [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) - [A Guide to Jdbi](http://www.baeldung.com/jdbi) - [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) @@ -14,3 +13,5 @@ - [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) - [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) - [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate) +- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) +- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index ded2b220f1..6d31467db3 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -2,3 +2,4 @@ - [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb) - [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging) +- [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index f76d994f9f..393d15d6f1 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -1,15 +1,14 @@ -========= - -## Spring Data JPA Example Project - -### Relevant Articles: -- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) -- [JPA Join Types](https://www.baeldung.com/jpa-join-types) -- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) -- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) -- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) -- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters) -- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) -- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) -- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) - +========= + +## Spring Data JPA Example Project + +### Relevant Articles: +- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) +- [JPA Join Types](https://www.baeldung.com/jpa-join-types) +- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) +- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) +- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) +- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters) +- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) +- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) +- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index f2553ad229..6f8d83aa9d 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -4,7 +4,6 @@ ### Relevant Articles: - [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring) -- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index 2fcd05e84a..af4e4427c7 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -5,6 +5,9 @@ ### Relevant Articles: - [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) +- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) +- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) + ### Eclipse Config diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index e624af4ea6..4057db8033 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -32,7 +32,16 @@ - + + org.hibernate + hibernate-core + ${hibernate.version} + + + javax.transaction + jta + ${jta.version} + org.hibernate hibernate-entitymanager @@ -55,6 +64,12 @@ ${h2.version} + + org.apache.tomcat + tomcat-dbcp + ${tomcat-dbcp.version} + + @@ -104,6 +119,8 @@ 5.4.2.Final 6.0.6 2.1.6.RELEASE + 9.0.0.M26 + 1.1 21.0 diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java new file mode 100644 index 0000000000..5fc932b256 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.bootstrap.model.TestEntity; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class BarHibernateDAO { + + @Autowired + private SessionFactory sessionFactory; + + public TestEntity findEntity(int id) { + + return getCurrentSession().find(TestEntity.class, 1); + } + + public void createEntity(TestEntity entity) { + + getCurrentSession().save(entity); + } + + public void createEntity(int id, String newDescription) { + + TestEntity entity = findEntity(id); + entity.setDescription(newDescription); + getCurrentSession().save(entity); + } + + public void deleteEntity(int id) { + + TestEntity entity = findEntity(id); + getCurrentSession().delete(entity); + } + + protected Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java new file mode 100644 index 0000000000..150e3778af --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.bootstrap; + +import com.google.common.base.Preconditions; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +public class HibernateConf { + + @Autowired + private Environment env; + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(dataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource dataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + + 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")); + + return hibernateProperties; + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java new file mode 100644 index 0000000000..b3e979478f --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java @@ -0,0 +1,24 @@ +package com.baeldung.hibernate.bootstrap; + +import com.google.common.base.Preconditions; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@EnableTransactionManagement +@ImportResource({ "classpath:hibernate5Configuration.xml" }) +public class HibernateXMLConf { + +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java new file mode 100644 index 0000000000..cae41db831 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.bootstrap.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class TestEntity { + + private int id; + + private String description; + + @Id + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java new file mode 100644 index 0000000000..5a6c76a93a --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java @@ -0,0 +1,14 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; + +import com.google.common.base.Preconditions; + +public abstract class AbstractDao implements IOperations { + + protected Class clazz; + + protected final void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java new file mode 100644 index 0000000000..f3ade67f80 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java @@ -0,0 +1,59 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Preconditions; + +@SuppressWarnings("unchecked") +public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { + + @Autowired + protected SessionFactory sessionFactory; + + // API + + @Override + public T findOne(final long id) { + return (T) getCurrentSession().get(clazz, id); + } + + @Override + public List findAll() { + return getCurrentSession().createQuery("from " + clazz.getName()).list(); + } + + @Override + public void create(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().saveOrUpdate(entity); + } + + @Override + public T update(final T entity) { + Preconditions.checkNotNull(entity); + return (T) getCurrentSession().merge(entity); + } + + @Override + public void delete(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + final T entity = findOne(entityId); + Preconditions.checkState(entity != null); + delete(entity); + } + + protected Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java new file mode 100644 index 0000000000..4ef99221ab --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java @@ -0,0 +1,20 @@ +package com.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + void create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java new file mode 100644 index 0000000000..2d940527e1 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java @@ -0,0 +1,20 @@ +package com.baeldung.persistence.dao.impl; + +import org.baeldung.persistence.dao.IFooDao; +import org.baeldung.persistence.model.Foo; +import org.springframework.stereotype.Repository; + +import com.baeldung.persistence.dao.common.AbstractHibernateDao; + +@Repository +public class FooDao extends AbstractHibernateDao implements IFooDao { + + public FooDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceConfig.java new file mode 100644 index 0000000000..c454ab3b54 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceConfig.java @@ -0,0 +1,118 @@ +package org.baeldung.config; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.baeldung.persistence.dao.IFooDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.baeldung.persistence.dao.impl.FooDao; +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") +@EnableJpaAuditing +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "com.baeldung.persistence" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(restDataSource()); + emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setJpaProperties(hibernateProperties()); + + return emf; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + + @Bean + public PlatformTransactionManager jpaTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + @Bean + public IFooDao fooHibernateDao() { + return new FooDao(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + + hibernateProperties.setProperty("hibernate.show_sql", "true"); + // hibernateProperties.setProperty("hibernate.format_sql", "true"); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + + // Envers properties + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Foo.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Foo.java index 5294860311..30635e9ef2 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Foo.java @@ -1,13 +1,25 @@ package org.baeldung.persistence.model; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; import java.io.Serializable; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; + +import org.hibernate.annotations.CacheConcurrencyStrategy; + @Entity @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) public class Foo implements Serializable { private static final long serialVersionUID = 1L; diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml new file mode 100644 index 0000000000..bbb61cb3e0 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml new file mode 100644 index 0000000000..cb6cf0aa5c --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties new file mode 100644 index 0000000000..b3cfd31f46 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties @@ -0,0 +1,13 @@ +# jdbc.X +jdbc.driverClassName=com.mysql.cj.jdbc.Driver +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true +jdbc.eventGeneratedId=tutorialuser +jdbc.pass=tutorialmy5ql + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop + +# envers.X +envers.audit_table_suffix=_audit_log diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql b/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql new file mode 100644 index 0000000000..9cedb75c37 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql @@ -0,0 +1,20 @@ +DELIMITER // + CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255)) + LANGUAGE SQL + DETERMINISTIC + SQL SECURITY DEFINER + BEGIN + SELECT * FROM foo WHERE name = fooName; + END // +DELIMITER ; + + +DELIMITER // + CREATE PROCEDURE GetAllFoos() + LANGUAGE SQL + DETERMINISTIC + SQL SECURITY DEFINER + BEGIN + SELECT * FROM foo; + END // +DELIMITER ; \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java new file mode 100644 index 0000000000..c41423643a --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java @@ -0,0 +1,185 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.bootstrap.model.TestEntity; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.Commit; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.transaction.TestTransaction; +import org.springframework.transaction.annotation.Transactional; + +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { HibernateConf.class }) +@Transactional +public class HibernateBootstrapIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + @Test + public void whenBootstrapHibernateSession_thenNoException() { + + Session session = sessionFactory.getCurrentSession(); + + TestEntity newEntity = new TestEntity(); + newEntity.setId(1); + session.save(newEntity); + + TestEntity searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + } + + @Test + public void whenProgrammaticTransactionCommit_thenEntityIsInDatabase() { + assertTrue(TestTransaction.isActive()); + + //Save an entity and commit. + Session session = sessionFactory.getCurrentSession(); + + TestEntity newEntity = new TestEntity(); + newEntity.setId(1); + session.save(newEntity); + + TestEntity searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + assertTrue(TestTransaction.isFlaggedForRollback()); + + TestTransaction.flagForCommit(); + TestTransaction.end(); + + assertFalse(TestTransaction.isFlaggedForRollback()); + assertFalse(TestTransaction.isActive()); + + //Check that the entity is still there in a new transaction, + //then delete it, but don't commit. + TestTransaction.start(); + + assertTrue(TestTransaction.isFlaggedForRollback()); + assertTrue(TestTransaction.isActive()); + + session = sessionFactory.getCurrentSession(); + searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + + session.delete(searchEntity); + session.flush(); + + TestTransaction.end(); + + assertFalse(TestTransaction.isActive()); + + //Check that the entity is still there in a new transaction, + //then delete it and commit. + TestTransaction.start(); + + session = sessionFactory.getCurrentSession(); + searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + + session.delete(searchEntity); + session.flush(); + + assertTrue(TestTransaction.isActive()); + + TestTransaction.flagForCommit(); + TestTransaction.end(); + + assertFalse(TestTransaction.isActive()); + + //Check that the entity is no longer there in a new transaction. + TestTransaction.start(); + + assertTrue(TestTransaction.isActive()); + + session = sessionFactory.getCurrentSession(); + searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNull(searchEntity); + } + + @Test + @Commit + public void givenTransactionCommitDefault_whenProgrammaticTransactionCommit_thenEntityIsInDatabase() { + assertTrue(TestTransaction.isActive()); + + //Save an entity and commit. + Session session = sessionFactory.getCurrentSession(); + + TestEntity newEntity = new TestEntity(); + newEntity.setId(1); + session.save(newEntity); + + TestEntity searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + assertFalse(TestTransaction.isFlaggedForRollback()); + + TestTransaction.end(); + + assertFalse(TestTransaction.isFlaggedForRollback()); + assertFalse(TestTransaction.isActive()); + + //Check that the entity is still there in a new transaction, + //then delete it, but don't commit. + TestTransaction.start(); + + assertFalse(TestTransaction.isFlaggedForRollback()); + assertTrue(TestTransaction.isActive()); + + session = sessionFactory.getCurrentSession(); + searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + + session.delete(searchEntity); + session.flush(); + + TestTransaction.flagForRollback(); + TestTransaction.end(); + + assertFalse(TestTransaction.isActive()); + + //Check that the entity is still there in a new transaction, + //then delete it and commit. + TestTransaction.start(); + + session = sessionFactory.getCurrentSession(); + searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + + session.delete(searchEntity); + session.flush(); + + assertTrue(TestTransaction.isActive()); + + TestTransaction.end(); + + assertFalse(TestTransaction.isActive()); + + //Check that the entity is no longer there in a new transaction. + TestTransaction.start(); + + assertTrue(TestTransaction.isActive()); + + session = sessionFactory.getCurrentSession(); + searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNull(searchEntity); + } + +} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java new file mode 100644 index 0000000000..5b811ad576 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.bootstrap.model.TestEntity; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { HibernateXMLConf.class }) +@Transactional +public class HibernateXMLBootstrapIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + @Test + public void whenBootstrapHibernateSession_thenNoException() { + + Session session = sessionFactory.getCurrentSession(); + + TestEntity newEntity = new TestEntity(); + newEntity.setId(1); + session.save(newEntity); + + TestEntity searchEntity = session.find(TestEntity.class, 1); + + Assert.assertNotNull(searchEntity); + } + +} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooStoredProceduresLiveTest.java new file mode 100644 index 0000000000..ded32e362e --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooStoredProceduresLiveTest.java @@ -0,0 +1,123 @@ +package org.baeldung.persistence.service; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.baeldung.config.PersistenceConfig; +import org.baeldung.persistence.model.Foo; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.exception.SQLGrammarException; +import org.hibernate.query.NativeQuery; +import org.hibernate.query.Query; +import org.junit.After; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class FooStoredProceduresLiveTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class); + + @Autowired + private SessionFactory sessionFactory; + + @Autowired + private FooService fooService; + + private Session session; + + @Before + public final void before() { + session = sessionFactory.openSession(); + Assume.assumeTrue(getAllFoosExists()); + Assume.assumeTrue(getFoosByNameExists()); + } + + private boolean getFoosByNameExists() { + try { + @SuppressWarnings("unchecked") + NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + sqlQuery.list(); + return true; + } catch (SQLGrammarException e) { + LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); + return false; + } + } + + private boolean getAllFoosExists() { + try { + @SuppressWarnings("unchecked") + NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + sqlQuery.list(); + return true; + } catch (SQLGrammarException e) { + LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); + return false; + } + } + + @After + public final void after() { + session.close(); + } + + @Test + public final void getAllFoosUsingStoredProcedures() { + + fooService.create(new Foo(randomAlphabetic(6))); + + // Stored procedure getAllFoos using createSQLQuery + @SuppressWarnings("unchecked") + NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + List allFoos = sqlQuery.list(); + for (Foo foo : allFoos) { + LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); + } + assertEquals(allFoos.size(), fooService.findAll().size()); + + // Stored procedure getAllFoos using a Named Query + @SuppressWarnings("unchecked") + Query namedQuery = session.getNamedQuery("callGetAllFoos"); + List allFoos2 = namedQuery.list(); + for (Foo foo : allFoos2) { + LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); + } + assertEquals(allFoos2.size(), fooService.findAll().size()); + } + + @Test + public final void getFoosByNameUsingStoredProcedures() { + + fooService.create(new Foo("NewFooName")); + + // Stored procedure getFoosByName using createSQLQuery() + @SuppressWarnings("unchecked") + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); + List allFoosByName = sqlQuery.list(); + for (Foo foo : allFoosByName) { + LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); + } + + // Stored procedure getFoosByName using getNamedQuery() + @SuppressWarnings("unchecked") + Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); + List allFoosByName2 = namedQuery.list(); + for (Foo foo : allFoosByName2) { + LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); + } + + } +} diff --git a/pom.xml b/pom.xml index 2ea5e4505c..9298c8ad17 100644 --- a/pom.xml +++ b/pom.xml @@ -635,7 +635,6 @@ spring-boot-custom-starter spring-boot-disable-console-logging - spring-boot-exceptions spring-boot-jasypt spring-boot-keycloak spring-boot-logging-log4j2 @@ -834,7 +833,6 @@ spring-boot-camel spring-boot-client spring-boot-custom-starter - spring-boot-exceptions greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app persistence-modules/spring-boot-h2/spring-boot-h2-database @@ -1297,7 +1295,6 @@ spring-boot-ctx-fluent spring-boot-custom-starter spring-boot-disable-console-logging - spring-boot-exceptions spring-boot-jasypt spring-boot-keycloak diff --git a/spring-5-webflux/README.md b/spring-5-webflux/README.md index 4345c8746b..e84ee863bf 100644 --- a/spring-5-webflux/README.md +++ b/spring-5-webflux/README.md @@ -2,4 +2,4 @@ - [Spring Boot Reactor Netty Configuration](https://www.baeldung.com/spring-boot-reactor-netty) - [How to Return 404 with Spring WebFlux](https://www.baeldung.com/spring-webflux-404) -- [WebClient request with parameters](https://www.baeldung.com/webclient-request-with-parameters) +- [Spring WebClient Requests with Parameters](https://www.baeldung.com/webflux-webclient-parameters) diff --git a/spring-boot-data/README.md b/spring-boot-data/README.md index d93b8c3e93..3fd1d17994 100644 --- a/spring-boot-data/README.md +++ b/spring-boot-data/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates) +- [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) diff --git a/spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/CustomException.java b/spring-boot-data/src/main/java/com/baeldung/jsonexception/CustomException.java similarity index 100% rename from spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/CustomException.java rename to spring-boot-data/src/main/java/com/baeldung/jsonexception/CustomException.java diff --git a/spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/ErrorHandler.java b/spring-boot-data/src/main/java/com/baeldung/jsonexception/ErrorHandler.java similarity index 73% rename from spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/ErrorHandler.java rename to spring-boot-data/src/main/java/com/baeldung/jsonexception/ErrorHandler.java index a890dfa3a2..9f82c4fc57 100644 --- a/spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/ErrorHandler.java +++ b/spring-boot-data/src/main/java/com/baeldung/jsonexception/ErrorHandler.java @@ -1,13 +1,11 @@ package com.baeldung.jsonexception; import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; -@ControllerAdvice -@ResponseBody +@RestControllerAdvice public class ErrorHandler { @ExceptionHandler(CustomException.class) diff --git a/spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/MainController.java b/spring-boot-data/src/main/java/com/baeldung/jsonexception/MainController.java similarity index 100% rename from spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/MainController.java rename to spring-boot-data/src/main/java/com/baeldung/jsonexception/MainController.java diff --git a/spring-boot-exceptions/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java similarity index 100% rename from spring-boot-exceptions/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java rename to spring-boot-data/src/test/java/com/baeldung/jsonexception/MainControllerIntegrationTest.java diff --git a/spring-boot-exceptions/.gitignore b/spring-boot-exceptions/.gitignore deleted file mode 100644 index 153c9335eb..0000000000 --- a/spring-boot-exceptions/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -HELP.md -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -/build/ - -### VS Code ### -.vscode/ diff --git a/spring-boot-exceptions/pom.xml b/spring-boot-exceptions/pom.xml deleted file mode 100644 index 01d6973642..0000000000 --- a/spring-boot-exceptions/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - 4.0.0 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - com.baeldung - spring-boot-exceptions - 0.0.4-SNAPSHOT - pass-exception-to-client-json-spring-boot - Baeldung article code on how to pass exceptions to client in JSON format using Spring Boot - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - - diff --git a/spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/JsonErrorApplication.java b/spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/JsonErrorApplication.java deleted file mode 100644 index 188584bd7c..0000000000 --- a/spring-boot-exceptions/src/main/java/com/baeldung/jsonexception/JsonErrorApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.jsonexception; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class JsonErrorApplication { - - public static void main(String[] args) { - SpringApplication.run(JsonErrorApplication.class, args); - } - -} \ No newline at end of file diff --git a/spring-boot-exceptions/src/main/resources/application.properties b/spring-boot-exceptions/src/main/resources/application.properties deleted file mode 100644 index 8b13789179..0000000000 --- a/spring-boot-exceptions/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - diff --git a/spring-boot-exceptions/src/main/resources/static/.gitignore b/spring-boot-exceptions/src/main/resources/static/.gitignore deleted file mode 100644 index 5e7d2734cf..0000000000 --- a/spring-boot-exceptions/src/main/resources/static/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Ignore everything in this directory -* -# Except this file -!.gitignore diff --git a/spring-boot-exceptions/src/main/resources/templates/.gitignore b/spring-boot-exceptions/src/main/resources/templates/.gitignore deleted file mode 100644 index 5e7d2734cf..0000000000 --- a/spring-boot-exceptions/src/main/resources/templates/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Ignore everything in this directory -* -# Except this file -!.gitignore diff --git a/spring-boot-exceptions/src/test/java/com/baeldung/jsonexception/SpringContextIntegrationTest.java b/spring-boot-exceptions/src/test/java/com/baeldung/jsonexception/SpringContextIntegrationTest.java deleted file mode 100644 index aa91e242ab..0000000000 --- a/spring-boot-exceptions/src/test/java/com/baeldung/jsonexception/SpringContextIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.jsonexception; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringContextIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index 356eca40bf..5be5c974d3 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -11,4 +11,4 @@ - [Comparing Embedded Servlet Containers in Spring Boot](http://www.baeldung.com/spring-boot-servlet-containers) - [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app) - [Spring Properties File Outside jar](https://www.baeldung.com/spring-properties-file-outside-jar) - - [EnvironmentPostProcessor in Spring Boot](https://www.baeldung.com/spring-boot-environmentpostprocessorr) + - [EnvironmentPostProcessor in Spring Boot](https://www.baeldung.com/spring-boot-environmentpostprocessor) diff --git a/testing-modules/junit-5-configuration/README.md b/testing-modules/junit-5-basics/README.md similarity index 100% rename from testing-modules/junit-5-configuration/README.md rename to testing-modules/junit-5-basics/README.md diff --git a/testing-modules/junit-5-configuration/pom.xml b/testing-modules/junit-5-basics/pom.xml similarity index 97% rename from testing-modules/junit-5-configuration/pom.xml rename to testing-modules/junit-5-basics/pom.xml index 0f19bc19b7..28afcd6aac 100644 --- a/testing-modules/junit-5-configuration/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -3,10 +3,10 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - junit-5-configuration + junit-5-basics 1.0-SNAPSHOT - junit-5-configuration - Intro to JUnit 5 configuration + junit-5-basics + Intro to JUnit 5 com.baeldung diff --git a/testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/Employee.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/Employee.java similarity index 100% rename from testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/Employee.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/Employee.java diff --git a/testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java similarity index 100% rename from testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java diff --git a/testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java similarity index 100% rename from testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java diff --git a/testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java similarity index 100% rename from testing-modules/junit-5-configuration/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java diff --git a/testing-modules/junit-5-configuration/src/main/resources/jdbc/schema.sql b/testing-modules/junit-5-basics/src/main/resources/jdbc/schema.sql similarity index 100% rename from testing-modules/junit-5-configuration/src/main/resources/jdbc/schema.sql rename to testing-modules/junit-5-basics/src/main/resources/jdbc/schema.sql diff --git a/testing-modules/junit-5-configuration/src/main/resources/jdbc/springJdbc-config.xml b/testing-modules/junit-5-basics/src/main/resources/jdbc/springJdbc-config.xml similarity index 100% rename from testing-modules/junit-5-configuration/src/main/resources/jdbc/springJdbc-config.xml rename to testing-modules/junit-5-basics/src/main/resources/jdbc/springJdbc-config.xml diff --git a/testing-modules/junit-5-configuration/src/main/resources/jdbc/test-data.sql b/testing-modules/junit-5-basics/src/main/resources/jdbc/test-data.sql similarity index 100% rename from testing-modules/junit-5-configuration/src/main/resources/jdbc/test-data.sql rename to testing-modules/junit-5-basics/src/main/resources/jdbc/test-data.sql diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/IntegrationTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/IntegrationTest.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/IntegrationTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/IntegrationTest.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/UnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/UnitTest.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/categories/UnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/categories/UnitTest.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/example/EmployeeUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/example/EmployeeUnitTest.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/example/EmployeeUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/example/EmployeeUnitTest.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java diff --git a/testing-modules/junit-5-configuration/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java similarity index 100% rename from testing-modules/junit-5-configuration/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java diff --git a/testing-modules/junit-5-configuration/src/test/resources/example_resource.txt b/testing-modules/junit-5-basics/src/test/resources/example_resource.txt similarity index 100% rename from testing-modules/junit-5-configuration/src/test/resources/example_resource.txt rename to testing-modules/junit-5-basics/src/test/resources/example_resource.txt diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index f27630a76d..84e0577cfe 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -21,24 +21,34 @@ junit-platform-engine ${junit.platform.version} + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + org.junit.jupiter junit-jupiter-params ${junit.jupiter.version} + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + org.junit.platform junit-platform-runner ${junit.platform.version} test - + org.junit.vintage junit-vintage-engine ${junit.vintage.version} test - + org.junit.jupiter junit-jupiter-migrationsupport ${junit.vintage.version} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java index 31b6e14d6c..f1f7c531f2 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java @@ -2,7 +2,21 @@ package com.baeldung; import static java.time.Duration.ofSeconds; import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.LinkedList; @@ -91,11 +105,12 @@ public class AssertionUnitTest { @Test public void givenMultipleAssertion_whenAssertingAll_thenOK() { + Object obj = null; assertAll( "heading", () -> assertEquals(4, 2 * 2, "4 is 2 times 2"), () -> assertEquals("java", "JAVA".toLowerCase()), - () -> assertEquals(null, null, "null is equal to null") + () -> assertEquals(obj, null, "null is equal to null") ); } diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/AlphanumericOrderUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/AlphanumericOrderUnitTest.java new file mode 100644 index 0000000000..d62ca0c666 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/AlphanumericOrderUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.junit5.order; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.MethodOrderer.Alphanumeric; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +@TestMethodOrder(Alphanumeric.class) +public class AlphanumericOrderUnitTest { + private static StringBuilder output = new StringBuilder(""); + + @Test + public void myATest() { + output.append("A"); + } + + @Test + public void myBTest() { + output.append("B"); + } + + @Test + public void myaTest() { + output.append("a"); + } + + @AfterAll + public static void assertOutput() { + assertEquals(output.toString(), "ABa"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/CustomOrder.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/CustomOrder.java new file mode 100644 index 0000000000..e76230de63 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/CustomOrder.java @@ -0,0 +1,12 @@ +package com.baeldung.junit5.order; + +import org.junit.jupiter.api.MethodDescriptor; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.MethodOrdererContext; + +public class CustomOrder implements MethodOrderer{ + @Override + public void orderMethods(MethodOrdererContext context) { + context.getMethodDescriptors().sort((MethodDescriptor m1, MethodDescriptor m2)->m1.getMethod().getName().compareToIgnoreCase(m2.getMethod().getName())); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/CustomOrderUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/CustomOrderUnitTest.java new file mode 100644 index 0000000000..fa45921879 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/CustomOrderUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.junit5.order; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +@TestMethodOrder(CustomOrder.class) +public class CustomOrderUnitTest { + private static StringBuilder output = new StringBuilder(""); + + @Test + public void myATest() { + output.append("A"); + } + + @Test + public void myBTest() { + output.append("B"); + } + + @Test + public void myaTest() { + output.append("a"); + } + + + @AfterAll + public static void assertOutput() { + assertEquals(output.toString(), "AaB"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/OrderAnnotationUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/OrderAnnotationUnitTest.java new file mode 100644 index 0000000000..3d931a4158 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/order/OrderAnnotationUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.junit5.order; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +@TestMethodOrder(OrderAnnotation.class) +public class OrderAnnotationUnitTest { + private static StringBuilder output = new StringBuilder(""); + + @Test + @Order(1) + public void firstTest() { + output.append("a"); + } + + @Test + @Order(2) + public void secondTest() { + output.append("b"); + } + + @Test + @Order(3) + public void thirdTest() { + output.append("c"); + } + + @AfterAll + public static void assertOutput() { + assertEquals(output.toString(), "abc"); + } +} diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 40ed63bc12..90ec857b7f 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -32,6 +32,6 @@ test-containers testing testng - junit-5-configuration + junit-5-basics