欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在spring中使用Hibernate5

程序员文章站 2023-11-26 09:52:46
[TOC] 1. Overview In this article, we’ll discuss how to bootstrap Hibernate 5 with Spring , using both Java and XML configuration. 2. Spring Integrati ......

1. overview

in this article, we’ll discuss how to bootstrap hibernate 5 with spring, using both java and xml configuration.

2. spring integration

bootstrapping a sessionfactory with the native hibernate api is a bit complicated and would take us quite a few lines of code (have a look at the official documentation in case you really need to do that).

fortunately, spring supports bootstrapping the sessionfactory so that we only need a few lines of java code or xml configuration.

also, before we jump in, if you’re working with older versions of hibernate, you can have a look at the articles about hibernate 3 as well as hibernate 4 with spring.

3. maven dependencies

let’s get started by first adding the necessary dependencies to our pom.xml:

<dependency>
    <groupid>org.hibernate</groupid>
    <artifactid>hibernate-core</artifactid>
    <version>5.4.2.final</version>
</dependency>

the spring-orm module provides the spring integration with hibernate:

<dependency>
    <groupid>org.springframework</groupid>
    <artifactid>spring-orm</artifactid>
    <version>5.1.6.release</version>
</dependency>

for the sake of simplicity, we’ll use h2 as our database:

<dependency>
    <groupid>com.h2database</groupid> 
    <artifactid>h2</artifactid>
    <version>1.4.197</version>
</dependency>

finally, we are going to use tomcat jdbc connection pooling, which fits better for production purposes than the drivermanagerdatasource provided by spring:

<dependency>
    <groupid>org.apache.tomcat</groupid>
    <artifactid>tomcat-dbcp</artifactid>
    <version>9.0.1</version>
</dependency>

4. configuration

as mentioned before, spring supports us with bootstrapping the hibernate sessionfactory.

all we have to do is to define some beans as well as a few parameters.

with spring, we have two options for these configurations, a java-based and an xml-based way.

4.1. using java configuration

for using hibernate 5 with spring, little has changed since hibernate 4: we have to use localsessionfactorybeanfrom the package org.springframework.orm.hibernate5 instead of org.springframework.orm.hibernate4.

like with hibernate 4 before, we have to define beans for localsessionfactorybean, datasource, and platformtransactionmanager, as well as some hibernate-specific properties.

let’s create our hibernateconfig class to configure hibernate 5 with spring:

@configuration
@enabletransactionmanagement
public class hibernateconf {
 
    @bean
    public localsessionfactorybean sessionfactory() {
        localsessionfactorybean sessionfactory = new localsessionfactorybean();
        sessionfactory.setdatasource(datasource());
        sessionfactory.setpackagestoscan(
          {"com.baeldung.hibernate.bootstrap.model" });
        sessionfactory.sethibernateproperties(hibernateproperties());
 
        return sessionfactory;
    }
 
    @bean
    public datasource datasource() {
        basicdatasource datasource = new basicdatasource();
        datasource.setdriverclassname("org.h2.driver");
        datasource.seturl("jdbc: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 supported, we can have a look at the list of supported dialects.

7. conclusion

in this quick tutorial, we configured spring with hibernate 5 – with both java and xml configuration.

as always, the full source code of the examples is available over on github.