[JAVA-19576] Initial commit (#14756)

* [JAVA-19576] Initial commit

* [JAVA-19576] Clean up

* [JAVA-19576] Clean up

* [JAVA-19576] Clean up
This commit is contained in:
panos-kakos 2023-09-25 06:54:17 +03:00 committed by GitHub
parent a3ab8131c9
commit e1ef148a37
33 changed files with 717 additions and 108 deletions

View File

@ -101,6 +101,7 @@
<module>spring-data-shardingsphere</module>
<!-- <module>spring-hibernate-3</module> FAILED -->
<!-- <module>spring-hibernate-5</module> FAILED --> <!-- long running -->
<module>spring-hibernate-6</module>
<module>spring-jpa</module>
<module>spring-jpa-2</module>
<module>spring-jdbc</module>

View File

@ -4,10 +4,7 @@ This module contains articles about Hibernate 5 with Spring.
### Relevant articles
- [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions)
- [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search)
- [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate)
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate)
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
- [Bootstrapping Hibernate 5 with Spring](https://www.baeldung.com/hibernate-5-spring)

View File

@ -1,24 +0,0 @@
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 {
}

View File

@ -1,44 +0,0 @@
package com.baeldung.hibernate.dynamicupdate;
import javax.transaction.Transactional;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
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 com.baeldung.hibernate.dynamicupdate.model.Account;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DynamicUpdateConfig.class, loader = AnnotationConfigContextLoader.class)
@Transactional
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DynamicUpdateIntegrationTest {
private static final Integer ACCOUNT_ID = 1;
@Autowired
private AccountRepository accountRepository;
@Test
@Commit
public void testA_whenTestAccountIsSaved_thenSuccess() {
Account account = new Account(ACCOUNT_ID, "account1", "regional", true);
accountRepository.save(account);
}
@Test
@Commit
// Enable Hibernate's debug logging in logback.xml to see the generated SQL statement.
public void testB_whenAccountNameUpdated_thenSuccess() {
Account account = accountRepository.findOne(ACCOUNT_ID);
account.setName("Test Account");
accountRepository.save(account);
}
}

View File

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

View File

@ -0,0 +1,9 @@
## Hibernate 5 with Spring
This module contains articles about Hibernate 6 with Spring.
### Relevant articles
- [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions)
- [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate)
- [Bootstrapping Hibernate 5 with Spring](https://www.baeldung.com/hibernate-5-spring)

View File

@ -0,0 +1,109 @@
<?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>
<artifactId>spring-hibernate-6</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-hibernate-6</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springframework.data.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat-dbcp.version}</version>
</dependency>
<!-- validation -->
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>${org.springframework.security.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
<properties>
<!-- Spring -->
<org.springframework.version>6.0.11</org.springframework.version>
<org.springframework.data.version>3.1.3</org.springframework.data.version>
<org.springframework.security.version>6.1.3</org.springframework.security.version>
<!-- persistence -->
<hibernate.version>6.2.8.Final</hibernate.version>
<mysql-connector-java.version>8.0.7-dmr</mysql-connector-java.version>
<tomcat-dbcp.version>9.0.80</tomcat-dbcp.version>
</properties>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.hibernate.bootstrap;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:hibernate6Configuration.xml" })
public class HibernateXMLConf {
}

View File

@ -1,7 +1,7 @@
package com.baeldung.hibernate.bootstrap.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class TestEntity {

View File

@ -2,7 +2,7 @@ package com.baeldung.hibernate.dynamicupdate;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import jakarta.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;

View File

@ -2,9 +2,9 @@ package com.baeldung.hibernate.dynamicupdate.model;
import java.text.MessageFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.hibernate.annotations.DynamicUpdate;

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.dao.common.IOperations;
public interface IFooDao extends IOperations<Foo> {
//
}

View File

@ -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);
}
}

View File

@ -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()).getResultList();
}
@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();
}
}

View File

@ -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);
}

View File

@ -0,0 +1,19 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.dao.IFooDao;
import com.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooHibernateDao extends AbstractHibernateDao<Foo> implements IFooDao {
public FooHibernateDao() {
super();
setClazz(Foo.class);
}
// API
}

View File

@ -0,0 +1,73 @@
package com.baeldung.persistence.model;
import jakarta.persistence.*;
import java.io.Serializable;
@Entity
public class Foo implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.spring;
import com.baeldung.persistence.dao.IFooDao;
import com.baeldung.persistence.dao.impl.FooHibernateDao;
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.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.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" })
@ComponentScan({ "com.baeldung.persistence" })
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource myDataSource() {
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 PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@Bean
public IFooDao fooHibernateDao() {
return new FooHibernateDao();
}
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", "false");
// Envers properties
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
return hibernateProperties;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.baeldung.persistence.dao", "com.baeldung.persistence.service" })
@ImportResource({ "classpath:hibernate6Config.xml" })
public class PersistenceXmlConfig {
}

View File

@ -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>

View File

@ -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>

View File

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

View File

@ -0,0 +1,22 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.eventGeneratedId=sa
jdbc.user=sa
jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
# hibernate.search.X
hibernate.search.default.directory_provider = filesystem
hibernate.search.default.indexBase = /data/index/default
# envers.X
envers.audit_table_suffix=_audit_log

View File

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

View File

@ -0,0 +1,13 @@
# jdbc.X
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
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

View File

@ -0,0 +1,19 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,33 +1,36 @@
package com.baeldung.hibernate.bootstrap;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
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.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.junit.jupiter.SpringExtension;
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 {
@ContextConfiguration(classes = { HibernateXMLConf.class })
@ExtendWith(SpringExtension.class)
class HibernateBootstrapIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
@Test
public void whenBootstrapHibernateSession_thenNoException() {
void whenBootstrapHibernateSession_thenNoException() {
Session session = sessionFactory.getCurrentSession();
@ -37,11 +40,11 @@ public class HibernateBootstrapIntegrationTest {
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertNotNull(searchEntity);
}
@Test
public void whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
void whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
assertTrue(TestTransaction.isActive());
//Save an entity and commit.
@ -53,7 +56,7 @@ public class HibernateBootstrapIntegrationTest {
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertTrue(TestTransaction.isFlaggedForRollback());
TestTransaction.flagForCommit();
@ -72,7 +75,7 @@ public class HibernateBootstrapIntegrationTest {
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
@ -88,7 +91,7 @@ public class HibernateBootstrapIntegrationTest {
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
@ -108,12 +111,12 @@ public class HibernateBootstrapIntegrationTest {
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNull(searchEntity);
assertNull(searchEntity);
}
@Test
@Commit
public void givenTransactionCommitDefault_whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
void givenTransactionCommitDefault_whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
assertTrue(TestTransaction.isActive());
//Save an entity and commit.
@ -125,7 +128,7 @@ public class HibernateBootstrapIntegrationTest {
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertNotNull(searchEntity);
assertFalse(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
@ -143,7 +146,7 @@ public class HibernateBootstrapIntegrationTest {
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
@ -160,7 +163,7 @@ public class HibernateBootstrapIntegrationTest {
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
@ -179,7 +182,7 @@ public class HibernateBootstrapIntegrationTest {
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNull(searchEntity);
assertNull(searchEntity);
}
}

View File

@ -1,26 +1,27 @@
package com.baeldung.hibernate.bootstrap;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { HibernateXMLConf.class })
@Transactional
public class HibernateXMLBootstrapIntegrationTest {
class HibernateXMLBootstrapIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
@Test
public void whenBootstrapHibernateSession_thenNoException() {
void whenBootstrapHibernateSession_thenNoException() {
Session session = sessionFactory.getCurrentSession();
@ -30,7 +31,7 @@ public class HibernateXMLBootstrapIntegrationTest {
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertNotNull(searchEntity);
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.hibernate.dynamicupdate;
import java.util.Optional;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.hibernate.dynamicupdate.model.Account;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { DynamicUpdateConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DynamicUpdateIntegrationTest {
private static final Integer ACCOUNT_ID = 1;
@Autowired
private AccountRepository accountRepository;
@Test
@Commit
@Order(1)
void testA_whenTestAccountIsSaved_thenSuccess() {
Account account = new Account(ACCOUNT_ID, "account1", "regional", true);
accountRepository.save(account);
}
@Test
@Commit
@Order(2)
// Enable Hibernate's debug logging in logback.xml to see the generated SQL statement.
void testB_whenAccountNameUpdated_thenSuccess() {
Optional<Account> account = accountRepository.findById(ACCOUNT_ID);
if(account.isPresent()){
account.get().setName("Test Account");
accountRepository.save(account.get());
}
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.persistence.dao.common;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.PersistenceConfig;
import org.apache.commons.lang3.RandomStringUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
class HibernateDaoIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
private Session session;
@BeforeEach
public final void before() {
session = sessionFactory.openSession();
}
@AfterEach
public final void after() {
session.close();
}
@Test
final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@Test
final void whenPersistEntity_thenSuccess() {
session.persist(new Foo(RandomStringUtils.randomAlphabetic(5).toUpperCase()));
}
}