Spring是最常用的Java EE框架之一,Hibernate是最流行的ORM框架。这就是为什么企业应用中经常使用Spring Hibernate组合的原因。最近,我写了很多关于Spring教程和Hibernate教程,所以长期以来都应该发布一篇关于Spring Hibernate集成的文章。
Spring Hibernate
今天在本教程中,我们将使用Spring 4并将其与Hibernate 3集成,然后将同一个项目更新为使用Hibernate 4。由于Spring和Hibernate都有许多版本,并且Spring ORM工件支持Hibernate 3和Hibernate 4,所以最好我列出我项目中使用的所有依赖关系。请注意,我已经注意到并非所有的Spring和Hibernate版本都兼容,以下版本对我有效,因此我认为它们是兼容的。如果您使用其他版本并收到java.lang.NoClassDefFoundError错误,则意味着它们不兼容。主要是因为Hibernate类从一个包移动到另一个包,导致此错误。例如,org.hibernate.engine.FilterDefinition类在最新的Hibernate版本中移动到org.hibernate.engine.spi.FilterDefinition。
- Spring框架版本:4.0.3.RELEASE
- Hibernate Core和Hibernate EntityManager版本:3.6.9.Final和4.3.5.Final
- Spring ORM版本:4.0.3.RELEASE
数据库设置
I am using MySQL database for my project, so below setup.sql script will create the necessary table for this example.
CREATE TABLE `Person` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '',
`country` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
commit;
Spring Hibernate集成示例项目结构
Maven 依赖
我们将首先查看我们的 pom.xml 文件,查看所有必需的依赖项及其版本。
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>SpringHibernateExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Spring -->
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<!-- <hibernate.version>4.3.5.Final</hibernate.version> -->
<hibernate.version>3.6.9.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring ORM support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
Spring 和 Hibernate 集成项目的重要依赖项为:
- spring-context 和 spring-tx 用于核心 Spring 功能。请注意,我正在使用版本 4.0.3.RELEASE。
- spring-orm 依赖项用于 Spring ORM 支持,这对于在我们的 Spring 项目中集成 hibernate 是必需的。
- hibernate-entitymanager 和 hibernate-core 依赖项用于 Hibernate 框架。请注意,版本为 3.6.9.Final,要使用 Hibernate 4,我们只需将其更改为 4.3.5.Final,如上述 pom.xml 文件中所注释的。
- mysql-connector-java 用于数据库连接的 MySQL 驱动程序。
模型类或实体 Bean
我们可以使用基于Hibernate XML的映射,也可以使用基于JPA注解的映射。这里我使用JPA注解进行映射,因为Hibernate提供了JPA实现。
package com.journaldev.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Entity bean with JPA annotations
* Hibernate provides JPA implementation
* @author pankaj
*
*/
@Entity
@Table(name="Person")
public class Person {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString(){
return "id="+id+", name="+name+", country="+country;
}
}
DAO类
我们将在DAO类中实现两个方法,第一个是将Person对象保存到表中,第二个是从表中获取所有记录并返回Person列表。
package com.journaldev.dao;
import java.util.List;
import com.journaldev.model.Person;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
}
上述DAO类的实现将如下所示。
package com.journaldev.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.model.Person;
public class PersonDAOImpl implements PersonDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void save(Person p) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(p);
tx.commit();
session.close();
}
@SuppressWarnings("unchecked")
@Override
public List<Person> list() {
Session session = this.sessionFactory.openSession();
List<Person> personList = session.createQuery("from Person").list();
session.close();
return personList;
}
}
请注意,这是我们唯一使用Hibernate相关类的地方。这种模式使得我们的实现灵活,并且易于从一种技术迁移到另一种技术。例如,如果我们想要使用iBatis ORM框架,我们所需做的就是为iBatis提供一个DAO实现,然后更改Spring bean配置文件。在上面的例子中,我正在使用Hibernate会话事务管理。但我们也可以使用Spring声明式事务管理,使用@Transactional
注解,详细内容请参阅Spring事务管理。
用于Hibernate 3集成的Spring Bean配置文件
让我们首先看一下我们需要为 Hibernate 3 集成所需的 Spring Bean 配置,稍后我们将详细讨论。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:aop="https://www.springframework.org/schema/aop"
xmlns:tx="https://www.springframework.org/schema/tx"
xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.0.xsd
https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/TestDB" />
<property name="username" value="pankaj" />
<property name="password" value="pankaj123" />
</bean>
<!-- Hibernate 3 XML SessionFactory Bean definition-->
<!-- <bean id="hibernate3SessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean> -->
<!-- Hibernate 3 Annotation SessionFactory Bean definition-->
<bean id="hibernate3AnnotatedSessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.journaldev.model.Person</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="personDAO" class="com.journaldev.dao.PersonDAOImpl">
<property name="sessionFactory" ref="hibernate3AnnotatedSessionFactory" />
</bean>
</beans>
有两种方式可以向 Hibernate 提供数据库连接详情,第一种是通过在hibernateProperties
中传递所有内容,第二种是创建一个数据源,然后将其传递给 Hibernate。我更喜欢第二种方法,这就是为什么我们有 Apache Commons DBCP 依赖来创建一个BasicDataSource
,通过设置数据库连接属性。对于 Spring 和 Hibernate 3 的集成,Spring ORM提供了两个类 – 当 Hibernate 映射是基于 XML 的时候使用org.springframework.orm.hibernate3.LocalSessionFactoryBean
,而基于注解的映射则使用org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
。我在注释中提供了LocalSessionFactoryBean
的简单bean配置,如果你正在使用基于 XML 的映射。AnnotationSessionFactoryBean
扩展了LocalSessionFactoryBean
类,因此它具有用于 Hibernate 集成的所有基本属性。这些属性是自解释的,大多与 Hibernate 相关,所以我不会过多详细介绍它们。但是,如果你想知道hibernateProperties,annotatedClasses是从哪里来的,你需要查看 bean 类的源代码。注意personDAO的bean定义,就像我之前说的,如果我们必须切换到其他 ORM 框架,我们需要在这里更改实现类并设置我们需要的任何其他属性。
Spring 4 Hibernate 3 测试程序
我们的设置已准备就绪,现在让我们编写一个简单的程序来测试我们的应用程序。
package com.journaldev.main;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.journaldev.dao.PersonDAO;
import com.journaldev.model.Person;
public class SpringHibernateMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
PersonDAO personDAO = context.getBean(PersonDAO.class);
Person person = new Person();
person.setName("Pankaj"); person.setCountry("India");
personDAO.save(person);
System.out.println("Person::"+person);
List list = personDAO.list();
for(Person p : list){
System.out.println("Person List::"+p);
}
//关闭资源
context.close();
}
}
当我们执行以上程序时,由于我没有正确设置日志记录,我们会得到与 Hibernate 相关的大量输出,但这超出了本教程的范围。但是我们得到了以下由我们的程序生成的输出。
Person::id=3, name=Pankaj, country=India
Person List::id=1, name=Pankaj, country=India
Person List::id=2, name=Pankaj, country=India
Person List::id=3, name=Pankaj, country=India
Spring 4 Hibernate 4 整合变更
现在让我们将我们的应用程序从 Hibernate 3 更改为 Hibernate 4。对于这次迁移,我们只需要进行以下配置更改。
-
在 pom.xml 文件中将 Hibernate 版本更改为 4.3.5.Final,如上面的注释所示。
-
更改Spring Bean配置文件,到目前为止,你一定已经明白了Spring Bean配置文件是整合Spring和Hibernate框架的关键。下面的Spring Bean配置文件适用于Spring 4和Hibernate 4版本。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:aop="https://www.springframework.org/schema/aop" xmlns:tx="https://www.springframework.org/schema/tx" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.0.xsd https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/TestDB" /> <property name="username" value="pankaj" /> <property name="password" value="pankaj123" /> </bean> <!-- Hibernate 4 SessionFactory Bean definition --> <bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>com.journaldev.model.Person</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.show_sql">false</prop> </props> </property> </bean> <bean id="personDAO" class="com.journaldev.dao.PersonDAOImpl"> <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </bean> </beans>
对于Hibernate 4,我们需要使用
org.springframework.orm.hibernate4.LocalSessionFactoryBean
作为SessionFactory Bean,Spring ORM已将Hibernate 3的两个类合并为一个类,现在只有一个类,这样做有助于避免混淆。所有其他配置与以前相同。
就是这样,我们的项目成功迁移到了Hibernate 4,很整洁,不是吗?只需将SpringHibernateMain
类更改为使用spring4.xml
作为bean配置,它就会正常工作,你将获得与以前相同的输出。你可以从下面的链接下载最终项目,并尝试更多的配置来学习更多。
Source:
https://www.digitalocean.com/community/tutorials/spring-hibernate-integration-example-tutorial