Merge branch 'master' into master
This commit is contained in:
commit
4169c6d431
|
@ -101,7 +101,7 @@ public class OptionalChainingUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
private Optional<String> createOptional(String input) {
|
private Optional<String> createOptional(String input) {
|
||||||
if (input == null || input == "" || input == "empty") {
|
if (input == null || "".equals(input) || "empty".equals(input)) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -6,4 +6,5 @@
|
||||||
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
|
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
|
||||||
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
|
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
|
||||||
- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
|
- [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)
|
- [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)
|
||||||
|
|
|
@ -5,7 +5,6 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
|
- [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)
|
- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
|
||||||
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
|
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
|
||||||
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
|
- [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)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
|
|
@ -2,3 +2,4 @@
|
||||||
|
|
||||||
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
|
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
|
||||||
- [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging)
|
- [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging)
|
||||||
|
- [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson)
|
||||||
|
|
|
@ -1,15 +1,14 @@
|
||||||
=========
|
=========
|
||||||
|
|
||||||
## Spring Data JPA Example Project
|
## Spring Data JPA Example Project
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
|
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
|
||||||
- [JPA Join Types](https://www.baeldung.com/jpa-join-types)
|
- [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)
|
- [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)
|
- [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 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 and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters)
|
||||||
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
|
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
|
||||||
- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable)
|
- [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 Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete)
|
||||||
|
|
||||||
|
|
|
@ -4,7 +4,6 @@
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring)
|
- [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)
|
- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination)
|
||||||
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
|
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
|
||||||
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
|
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
|
||||||
|
|
|
@ -5,6 +5,9 @@
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
|
- [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
|
### Eclipse Config
|
||||||
|
|
|
@ -32,7 +32,16 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- persistence -->
|
<!-- persistence -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-core</artifactId>
|
||||||
|
<version>${hibernate.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.transaction</groupId>
|
||||||
|
<artifactId>jta</artifactId>
|
||||||
|
<version>${jta.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.hibernate</groupId>
|
||||||
<artifactId>hibernate-entitymanager</artifactId>
|
<artifactId>hibernate-entitymanager</artifactId>
|
||||||
|
@ -55,6 +64,12 @@
|
||||||
<version>${h2.version}</version>
|
<version>${h2.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.tomcat</groupId>
|
||||||
|
<artifactId>tomcat-dbcp</artifactId>
|
||||||
|
<version>${tomcat-dbcp.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- utils -->
|
<!-- utils -->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -104,6 +119,8 @@
|
||||||
<hibernate.version>5.4.2.Final</hibernate.version>
|
<hibernate.version>5.4.2.Final</hibernate.version>
|
||||||
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
|
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
|
||||||
<spring-data-jpa.version>2.1.6.RELEASE</spring-data-jpa.version>
|
<spring-data-jpa.version>2.1.6.RELEASE</spring-data-jpa.version>
|
||||||
|
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
|
||||||
|
<jta.version>1.1</jta.version>
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>21.0</guava.version>
|
<guava.version>21.0</guava.version>
|
||||||
|
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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 {
|
||||||
|
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.persistence.dao.common;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
import com.google.common.base.Preconditions;
|
||||||
|
|
||||||
|
public abstract class AbstractDao<T extends Serializable> implements IOperations<T> {
|
||||||
|
|
||||||
|
protected Class<T> clazz;
|
||||||
|
|
||||||
|
protected final void setClazz(final Class<T> clazzToSet) {
|
||||||
|
clazz = Preconditions.checkNotNull(clazzToSet);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,59 @@
|
||||||
|
package com.baeldung.persistence.dao.common;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.hibernate.SessionFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
|
||||||
|
import com.google.common.base.Preconditions;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public abstract class AbstractHibernateDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
protected SessionFactory sessionFactory;
|
||||||
|
|
||||||
|
// API
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public T findOne(final long id) {
|
||||||
|
return (T) getCurrentSession().get(clazz, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<T> findAll() {
|
||||||
|
return getCurrentSession().createQuery("from " + clazz.getName()).list();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void create(final T entity) {
|
||||||
|
Preconditions.checkNotNull(entity);
|
||||||
|
getCurrentSession().saveOrUpdate(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public T update(final T entity) {
|
||||||
|
Preconditions.checkNotNull(entity);
|
||||||
|
return (T) getCurrentSession().merge(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(final T entity) {
|
||||||
|
Preconditions.checkNotNull(entity);
|
||||||
|
getCurrentSession().delete(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteById(final long entityId) {
|
||||||
|
final T entity = findOne(entityId);
|
||||||
|
Preconditions.checkState(entity != null);
|
||||||
|
delete(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Session getCurrentSession() {
|
||||||
|
return sessionFactory.getCurrentSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.persistence.dao.common;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface IOperations<T extends Serializable> {
|
||||||
|
|
||||||
|
T findOne(final long id);
|
||||||
|
|
||||||
|
List<T> findAll();
|
||||||
|
|
||||||
|
void create(final T entity);
|
||||||
|
|
||||||
|
T update(final T entity);
|
||||||
|
|
||||||
|
void delete(final T entity);
|
||||||
|
|
||||||
|
void deleteById(final long entityId);
|
||||||
|
|
||||||
|
}
|
|
@ -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<Foo> implements IFooDao {
|
||||||
|
|
||||||
|
public FooDao() {
|
||||||
|
super();
|
||||||
|
|
||||||
|
setClazz(Foo.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
// API
|
||||||
|
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,13 +1,25 @@
|
||||||
package org.baeldung.persistence.model;
|
package org.baeldung.persistence.model;
|
||||||
|
|
||||||
import org.hibernate.annotations.CacheConcurrencyStrategy;
|
|
||||||
|
|
||||||
import javax.persistence.*;
|
|
||||||
import java.io.Serializable;
|
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
|
@Entity
|
||||||
@Cacheable
|
@Cacheable
|
||||||
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
|
@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 {
|
public class Foo implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
|
@ -0,0 +1,34 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||||
|
xsi:schemaLocation="
|
||||||
|
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||||
|
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||||
|
>
|
||||||
|
|
||||||
|
<context:property-placeholder location="classpath:persistence-mysql.properties"/>
|
||||||
|
|
||||||
|
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
|
||||||
|
<property name="dataSource" ref="dataSource"/>
|
||||||
|
<property name="packagesToScan" value="com.baeldung.persistence.model"/>
|
||||||
|
<property name="hibernateProperties">
|
||||||
|
<props>
|
||||||
|
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||||
|
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||||
|
</props>
|
||||||
|
</property>
|
||||||
|
</bean>
|
||||||
|
|
||||||
|
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
|
||||||
|
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||||
|
<property name="url" value="${jdbc.url}"/>
|
||||||
|
<property name="username" value="${jdbc.eventGeneratedId}"/>
|
||||||
|
<property name="password" value="${jdbc.pass}"/>
|
||||||
|
</bean>
|
||||||
|
|
||||||
|
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
|
||||||
|
<property name="sessionFactory" ref="sessionFactory"/>
|
||||||
|
</bean>
|
||||||
|
|
||||||
|
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
|
||||||
|
|
||||||
|
</beans>
|
|
@ -0,0 +1,30 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||||
|
xsi:schemaLocation="
|
||||||
|
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||||
|
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
|
||||||
|
|
||||||
|
<context:property-placeholder location="classpath:persistence-h2.properties"/>
|
||||||
|
|
||||||
|
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
|
||||||
|
<property name="dataSource" ref="dataSource"/>
|
||||||
|
<property name="packagesToScan" value="com.baeldung.hibernate.bootstrap.model"/>
|
||||||
|
<property name="hibernateProperties">
|
||||||
|
<props>
|
||||||
|
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||||
|
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||||
|
</props>
|
||||||
|
</property>
|
||||||
|
</bean>
|
||||||
|
|
||||||
|
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
|
||||||
|
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||||
|
<property name="url" value="${jdbc.url}"/>
|
||||||
|
<property name="username" value="${jdbc.user}"/>
|
||||||
|
<property name="password" value="${jdbc.pass}"/>
|
||||||
|
</bean>
|
||||||
|
|
||||||
|
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
|
||||||
|
<property name="sessionFactory" ref="sessionFactory"/>
|
||||||
|
</bean>
|
||||||
|
</beans>
|
|
@ -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
|
|
@ -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 ;
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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<Foo> 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<Foo> 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<Foo> sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||||
|
List<Foo> 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<Foo> namedQuery = session.getNamedQuery("callGetAllFoos");
|
||||||
|
List<Foo> 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<Foo> sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
|
||||||
|
List<Foo> allFoosByName = sqlQuery.list();
|
||||||
|
for (Foo foo : allFoosByName) {
|
||||||
|
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stored procedure getFoosByName using getNamedQuery()
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Query<Foo> namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
|
||||||
|
List<Foo> allFoosByName2 = namedQuery.list();
|
||||||
|
for (Foo foo : allFoosByName2) {
|
||||||
|
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
3
pom.xml
3
pom.xml
|
@ -635,7 +635,6 @@
|
||||||
<module>spring-boot-custom-starter</module>
|
<module>spring-boot-custom-starter</module>
|
||||||
<module>spring-boot-disable-console-logging</module>
|
<module>spring-boot-disable-console-logging</module>
|
||||||
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
|
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
|
||||||
<module>spring-boot-exceptions</module>
|
|
||||||
<module>spring-boot-jasypt</module>
|
<module>spring-boot-jasypt</module>
|
||||||
<module>spring-boot-keycloak</module>
|
<module>spring-boot-keycloak</module>
|
||||||
<module>spring-boot-logging-log4j2</module>
|
<module>spring-boot-logging-log4j2</module>
|
||||||
|
@ -834,7 +833,6 @@
|
||||||
<module>spring-boot-camel</module>
|
<module>spring-boot-camel</module>
|
||||||
<module>spring-boot-client</module>
|
<module>spring-boot-client</module>
|
||||||
<module>spring-boot-custom-starter</module>
|
<module>spring-boot-custom-starter</module>
|
||||||
<module>spring-boot-exceptions</module>
|
|
||||||
<module>greeter-spring-boot-autoconfigure</module>
|
<module>greeter-spring-boot-autoconfigure</module>
|
||||||
<module>greeter-spring-boot-sample-app</module>
|
<module>greeter-spring-boot-sample-app</module>
|
||||||
<module>persistence-modules/spring-boot-h2/spring-boot-h2-database</module>
|
<module>persistence-modules/spring-boot-h2/spring-boot-h2-database</module>
|
||||||
|
@ -1297,7 +1295,6 @@
|
||||||
<module>spring-boot-ctx-fluent</module>
|
<module>spring-boot-ctx-fluent</module>
|
||||||
<module>spring-boot-custom-starter</module>
|
<module>spring-boot-custom-starter</module>
|
||||||
<module>spring-boot-disable-console-logging</module>
|
<module>spring-boot-disable-console-logging</module>
|
||||||
<module>spring-boot-exceptions</module>
|
|
||||||
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
|
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
|
||||||
<module>spring-boot-jasypt</module>
|
<module>spring-boot-jasypt</module>
|
||||||
<module>spring-boot-keycloak</module>
|
<module>spring-boot-keycloak</module>
|
||||||
|
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
- [Spring Boot Reactor Netty Configuration](https://www.baeldung.com/spring-boot-reactor-netty)
|
- [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)
|
- [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)
|
||||||
|
|
|
@ -1,2 +1,3 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates)
|
- [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)
|
||||||
|
|
|
@ -1,13 +1,11 @@
|
||||||
package com.baeldung.jsonexception;
|
package com.baeldung.jsonexception;
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
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.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.ResponseBody;
|
|
||||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
|
||||||
@ControllerAdvice
|
@RestControllerAdvice
|
||||||
@ResponseBody
|
|
||||||
public class ErrorHandler {
|
public class ErrorHandler {
|
||||||
|
|
||||||
@ExceptionHandler(CustomException.class)
|
@ExceptionHandler(CustomException.class)
|
|
@ -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/
|
|
|
@ -1,33 +0,0 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-boot-2</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<relativePath>../parent-boot-2</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>spring-boot-exceptions</artifactId>
|
|
||||||
<version>0.0.4-SNAPSHOT</version>
|
|
||||||
<name>pass-exception-to-client-json-spring-boot</name>
|
|
||||||
<description>Baeldung article code on how to pass exceptions to client in JSON format using Spring Boot</description>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,4 +0,0 @@
|
||||||
# Ignore everything in this directory
|
|
||||||
*
|
|
||||||
# Except this file
|
|
||||||
!.gitignore
|
|
|
@ -1,4 +0,0 @@
|
||||||
# Ignore everything in this directory
|
|
||||||
*
|
|
||||||
# Except this file
|
|
||||||
!.gitignore
|
|
|
@ -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() {
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -11,4 +11,4 @@
|
||||||
- [Comparing Embedded Servlet Containers in Spring Boot](http://www.baeldung.com/spring-boot-servlet-containers)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
|
|
@ -3,10 +3,10 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>junit-5-configuration</artifactId>
|
<artifactId>junit-5-basics</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
<name>junit-5-configuration</name>
|
<name>junit-5-basics</name>
|
||||||
<description>Intro to JUnit 5 configuration</description>
|
<description>Intro to JUnit 5</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
|
@ -21,24 +21,34 @@
|
||||||
<artifactId>junit-platform-engine</artifactId>
|
<artifactId>junit-platform-engine</artifactId>
|
||||||
<version>${junit.platform.version}</version>
|
<version>${junit.platform.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
|
<version>${junit.jupiter.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter-params</artifactId>
|
<artifactId>junit-jupiter-params</artifactId>
|
||||||
<version>${junit.jupiter.version}</version>
|
<version>${junit.jupiter.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>${junit.jupiter.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.platform</groupId>
|
<groupId>org.junit.platform</groupId>
|
||||||
<artifactId>junit-platform-runner</artifactId>
|
<artifactId>junit-platform-runner</artifactId>
|
||||||
<version>${junit.platform.version}</version>
|
<version>${junit.platform.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.vintage</groupId>
|
<groupId>org.junit.vintage</groupId>
|
||||||
<artifactId>junit-vintage-engine</artifactId>
|
<artifactId>junit-vintage-engine</artifactId>
|
||||||
<version>${junit.vintage.version}</version>
|
<version>${junit.vintage.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter-migrationsupport</artifactId>
|
<artifactId>junit-jupiter-migrationsupport</artifactId>
|
||||||
<version>${junit.vintage.version}</version>
|
<version>${junit.vintage.version}</version>
|
||||||
|
|
|
@ -2,7 +2,21 @@ package com.baeldung;
|
||||||
|
|
||||||
import static java.time.Duration.ofSeconds;
|
import static java.time.Duration.ofSeconds;
|
||||||
import static java.util.Arrays.asList;
|
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.ArrayList;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
|
@ -91,11 +105,12 @@ public class AssertionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
|
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
|
||||||
|
Object obj = null;
|
||||||
assertAll(
|
assertAll(
|
||||||
"heading",
|
"heading",
|
||||||
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
|
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
|
||||||
() -> assertEquals("java", "JAVA".toLowerCase()),
|
() -> assertEquals("java", "JAVA".toLowerCase()),
|
||||||
() -> assertEquals(null, null, "null is equal to null")
|
() -> assertEquals(obj, null, "null is equal to null")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -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()));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -32,6 +32,6 @@
|
||||||
<module>test-containers</module>
|
<module>test-containers</module>
|
||||||
<module>testing</module>
|
<module>testing</module>
|
||||||
<module>testng</module>
|
<module>testng</module>
|
||||||
<module>junit-5-configuration</module>
|
<module>junit-5-basics</module>
|
||||||
</modules>
|
</modules>
|
||||||
</project>
|
</project>
|
||||||
|
|
Loading…
Reference in New Issue