Spring 集成 Hibernate
Spring 对于大量的 ORM 框架 进行了集成支持,提供了更加方便的基础设施搭建,统一的异常封装,统一的的事务管理,同时允许混用多个 ORM 框架;
Spring 支持 Hibernate 的最低版本为 Hibernate 3.6,提供了Spring 风格的更加简便的配置方式,同时提供了 HibernateTemplate 模板类,用于降低 Hibernate 的使用难度;
一个简单的示例
示例代码模块:
site/assad/domain/User(领域对象)
site/assad/dao/UserDao(DAO对象)
site/assad/servcie/UserServcie(Service对象)
site/assad/applicationContext.xml(spring 配置文件)
配置文件
applicationContext.xml
(这里使用Spring风格的配置方式,可以不使用Hibernate的配置文件)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
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">
<!--扫描bena-->
<context:component-scan base-package="site.assad.dao" />
<context:component-scan base-package="site.assad.service" />
<!--配置属性占位符空间-->
<context:property-placeholder location="classpath:site/assad/jdbc.properties" />
<!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<!--配置 Hibernate 的 SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" >
<!--自动扫描标记注解的 Hibernate 实体类-->
<property name="packagesToScan" value="site.assad.domain" />
<!--指定 Hibernate 配置的属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!--配置 HibernateTempalte 模板类-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"
p:sessionFactory-ref="sessionFactory" />
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<!--自动扫描注解声明式事务管理切面-->
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
</beans>
领域对象 User,使用注解的方式配置 Hibernate 实体类
package site.assad.domain;
name="users") (
public class User implements Serializable{
strategy=GenerationType.IDENTITY) (
name="user_id") (
private int id;