reset password

MySQL and Hibernate

There are many different ways to configure Hibernate with Spring - first of all you can use either JPA or Hibernate Session, and then you have various choices like using hibernate.cfg.xml or not using one, specifying database information in Spring or in Hibernate, creating a data source in Spring or getting one from JNDI, and so on. Here I'll describe the way that I think is the best and the simplest.

1. Install MySQL database server as described here. MySQL 5.5 or above is required for this project. The sample code in the rest of the section is for MySQL 8.0.

2. Add the following dependencies to the Spring MVC application we created in the previous step::

  • org.hibernate:hibernate-entitymanager:5.4.4.Final
  • org.springframework:spring-orm:5.1.9.RELEASE
  • mysql:mysql-connector-java:8.0.17
  • org.apache.tomcat:tomcat-jdbc

tomcat-jdbc is for database connection pooling under Tomcat, and you should choose the version that matches the version of your Tomcat server.

3. Add a file src/main/resources/META-INF/persistence.xml as follows:

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">

    <persistence-unit name="springmvc">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect" />
        </properties>
    </persistence-unit>

</persistence>

This file provides the information about the JPA Entity Manager provider.

4. Add the following to web.xml:

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>jpaFilter</filter-name>  
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>  
    </filter>  

    <filter-mapping>  
        <filter-name>jpaFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>

The ContextLoaderListener will load another Spring bean configuration file, and by default the file is /WEB-INF/applicationContext.xml. This bean configuration file is not absolutely necessary for this step - we could put all the Hibernate/database beans in springmvc-servlet.xml, but this file is required later when we add security to the application, and it is customary to put beans that are not related to the web tier in applicationContext.xml as oppose to <dispatcher-servlet-name>-servlet.xml, which is sometimes referred to as the servlet context.

The jpaFilter keeps the entity manager open until after the view is rendered; without it Hibernate won't be able to load lazy collections in JSP.

5. Create a file /WEB-INF/applicationContext.xml as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/springmvc?allowPublicKeyRetrieval=true&amp;useSSL=false" />
        <property name="username" value="cysun" />
        <property name="password" value="abcd" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="springmvc" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <context:annotation-config />

    <tx:annotation-driven />

    <context:component-scan base-package="springmvc.model" />

</beans>

It adds four beans: a data source, an entity manager factory, a transaction manager, and an exception translator that translates various SQL/database exceptions into a Spring exception. <context:annotation-config> enables annotations like @Autowired and @PersistenceContext (which is like an @Autowired specifically for entity manager), <tx:annotation-driven> enables annotations like @Transactional, and <context:component-scan> looks for beans under the package springmvc.model and its sub-packages (presumably that's where your DAO classes are located).

And that is it. Now the application is a web application with both Spring and Hibernate. Here is some code you can use for testing:

This page has been viewed 23346 times.