:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return hibernateProperties;
}
}
4.2. Using XML Configuration
As a secondary option, we can also configure Hibernate 5 with an XML-based configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
<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">
create-drop
</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.H2Dialect
</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:db;DB_CLOSE_DELAY=-1"/>
<property name="username" value="sa"/>
<property name="password" value="sa"/>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
As we can easily see, we’re defining exactly the same beans and parameters as in the Java-based configuration earlier.
To bootstrap the XML into the Spring context, we can use a simple Java configuration file if the application is configured with Java configuration:
@Configuration
@EnableTransactionManagement
@ImportResource({"classpath:hibernate5Configuration.xml"})
public class HibernateXMLConf {
//
}
Alternatively, we can simply provide the XML file to the Spring Context, if the overall configuration is purely XML.
5. Usage
At this point, Hibernate 5 is fully configured with Spring, and we can inject the raw Hibernate SessionFactory directly whenever we need to:
public abstract class BarHibernateDAO {
@Autowired
private SessionFactory sessionFactory;
// ...
}
6. Supported Databases
Unfortunately, the Hibernate project doesn’t exactly provide an official list of supported databases.
That being said, it’s easy to see if a particular database type might be supp