首页 > 其他分享 >Spring与Hibernate的整合

Spring与Hibernate的整合

时间:2023-04-23 11:02:17浏览次数:26  
标签:sessionFactory Hibernate Spring REQUIRED SessionFactory PROPAGATION 整合 org impor


1. Spring与Hibernate的整合

1.1. 在Spring容器中创建SessionFactory

为了避免硬编码的资源查找与应用程序对象紧密耦合,Spring允许你在Spring容器中以bean的方式定义诸如JDBC DataSource或者Hibernate SessionFactory 的数据访问资源。任何需要进行资源访问的应用程序对象只需要持有这些事先定义好的实例的引用,下面的代码演示如何创建一个JDBC DataSource 和Hibernate SessionFactory 。

在ApplicationContext.xml文件中进行如下配置:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
</property>
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl">
</property>
<property name="username" value="scott"></property>
<property name="password" value="tiger"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle9Dialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>
com/morris/school/dao/entity/Department.hbm.xml
</value>
</list>
</property>
</bean>

在应用程序中可以如下使用:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
SessionFactory sessionFactory = (SessionFactory) applicationContext
.getBean("sessionFactory");

1.2. 基于Hibernate3的原生API实现DAO

DepartmentDapImpl.java

package com.morris.school.dao.jdbc;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.morris.school.dao.IDepartmentDao;
import com.morris.school.dao.entity.Department;
public class DepartmentDapImpl implements IDepartmentDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void addDepartment(Department dept) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(dept);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
}

在spring配置文件中如下配置:

<bean id="deptDao" class="com.morris.school.dao.jdbc.DepartmentDapImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

1.3. 基于Spring的DAO实现

HibernateDaoSupport 基类提供了访问与当前事务绑定的 Session 对象的函数,因而能保证在这种情况下异常的正确转化。 类似的函数同样可以在 SessionFactoryUtils 类中找到,但他们以静态方法的形式出现。 值得注意的是,通常将 'false' 作为参数值(表示是否允许创建)传递给 getSession(..) 方法进行调用。 此时,整个调用将在同一个事务内完成(它的整个生命周期由事务控制,避免了关闭返回的 Session 的需要)。

package com.morris.school.dao.jdbc;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.morris.school.dao.IDepartmentDao;
import com.morris.school.dao.entity.Department;
public class DepartmentDapImpl extends HibernateDaoSupport implements IDepartmentDao {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
IDepartmentDao deptDao = (IDepartmentDao) applicationContext
.getBean("deptDao");
deptDao.addDepartment(new Department("4", "后勤部"));
}
public void addDepartment(Department dept) {
this.getHibernateTemplate().save(dept);
}
}

1.4. 单个事务管理的配置

<!-- 目标对象 -->
<bean id="deptDao" class="com.morris.school.dao.jdbc.DepartmentDapImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 切面 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 代理对象 -->
<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<!-- 目标对象 -->
<property name="target" ref="deptDao"></property>
<!-- 切面 -->
<property name="transactionManager" ref="transactionManager"></property>
<property name="proxyTargetClass" value="true">
</property>
<!-- 属性模板 -->
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="do*">PROPAGATION_REQUIRED</prop>
<prop key="query*">readOnly</prop>
<prop key="find*">readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
<!--
PROPAGATION_REQUIRED == 支持当前事务,如果当前没有事务则重新创建一个事务。
PROPAGATION_SUPPORTS == 支持当前事务,如果当前没有事务则以非事务方式执行 readonly ==
就是只读,设置操作权限为只读,一般用于查询
-->
</props>
</property>
</bean>

1.5. 公共事务的配置

<!-- 目标对象 -->
<bean id="deptDao" class="com.morris.school.dao.jdbc.DepartmentDapImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 切面 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 公共事务代理 -->
<bean id="baseTransactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true" lazy-init="true">
<!-- 切面 -->
<property name="transactionManager" ref="transactionManager"></property>
<!-- 属性模板 -->
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="do*">PROPAGATION_REQUIRED</prop>
<prop key="query*">readOnly</prop>
<prop key="find*">readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
<!--
PROPAGATION_REQUIRED == 支持当前事务,如果当前没有事务则重新创建一个事务。
PROPAGATION_SUPPORTS == 支持当前事务,如果当前没有事务则以非事务方式执行 readonly ==
就是只读,设置操作权限为只读,一般用于查询
-->
</props>
</property>
</bean>
<bean id="userDaoProxy" parent="baseTransactionProxy">
<property name="target" ref="deptDao"></property>
</bean>

标签:sessionFactory,Hibernate,Spring,REQUIRED,SessionFactory,PROPAGATION,整合,org,impor
From: https://blog.51cto.com/u_6784072/6216864

相关文章

  • Hibernate对象的CRUD操作
    1.  Hibernate对象的CRUD操作1.1. 对象的三种状态瞬时(Transient)-由new操作符创建,且尚未与HibernateSession关联的对象被认定为瞬时(Transient)的。瞬时(Transient)对象不会被持久化到数据库中,也不会被赋予持久化标识(identifier)。如果瞬时(Transient)对象在程序中没有被......
  • Hibernate HQL详解
    1.  HibernateHQL详解1.1. hql简介Hibernate配备了一种非常强大的查询语言,这种语言看上去很像SQL。但是不要被语法结构上的相似所迷惑,HQL是非常有意识的被设计为完全面向对象的查询,它可以理解如继承、多态和关联之类的概念。看个示例,看看sql和HQL的相同与不同:Sql:select*......
  • Hibernate关联关系映射
    1.  Hibernate关联关系映射1.1. onetoone<classname="Person"><idname="id"column="personId"><generatorclass="native"/></id><jointable="PersonAddress"......
  • spring mvc一个Controller响应多个请求
    1.1. 控制器的实现packagecom.morris.controller;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.springframework.web.servlet.ModelAndView;importorg.springframework.web.servlet.mvc.multiaction.Multi......
  • spring集成Hessian
    1.1.1.   编写远程接口Ihello.javapackagecn.tempus.hessian;publicinterfaceIHello{publicStringsayHello(Stringname);}1.1.2.   编写远程接口实现类HelloImpl.javapackagecn.tempus.hessian;importcom.caucho.hessian.server.HessianServlet;......
  • spring mvc注解基本配置
    1.1. 配置web.xml<?xmlversion="1.0"encoding="UTF-8"?><web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xm......
  • 【spring boot】 重启kafka客户端连接
    背景kafka服务端重建时,kafka客户端会连不上kafka服务端,此时需要重启客户端重连代码实现@ServicepublicclassKafkaConsumerService{privateKafkaConsumer<String,String>consumer;@AutowiredprivateKafkaPropertieskafkaProperties;//在应用......
  • Spring缓存注解的使用与源码分析
    SpringCache提供了一个对缓存使用的抽象,以及大量的实现方便开发者使用。SpringCache主要提供了如下注解:注解说明@Cacheable根据方法的请求参数对其结果进行缓存@CachePut根据方法的请求参数对其结果进行缓存,和@Cacheable不同的是,它每次都会触发真实方法的调用@CacheEvict根据一定......
  • SpringMVC启动流程源码分析
    SpringMVC向WEB容器中注入了两个对象:ContextLoaderListener:由AbstractContextLoaderInitializer注入。DispatcherServlet:由AbstractDispatcherServletInitializer注入。下面分别分析这两个对象在WEB容器启动时做了什么工作?ContextLoaderListenerContextLoaderListener实现了Servle......
  • 为spring boot定制启动banner
    直接打开这个网站 https://patorjk.com/software/taag/#p=testall&f=Larry%203D&t=Type%20Something%20 输入你想要的文字内容,点TestAll即可,我们这里选择的字体是:Larry3D,你也可以根据喜好,选择自己想要的字体 复制并保存到src/main/resources/banner.txt即可 参考资料:......