Spring與Hibernate的整合,springhibernate

來源:互聯網
上載者:User

Spring與Hibernate的整合,springhibernate
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>


spring與hibernate整合:spring-hibernatejar

Spring和Hibernate整合 Spring配置: <?xml version="1.0" encoding="GBK"?> <!-- beans是Spring設定檔的根項目,並且指定了Schema資訊 --> <beans xmlns=" www.springframework.org/schema/beans" xmlns:xsi=" www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" www.springframework.org/schema/beans www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 定義資料來源Bean,使用C3P0資料來源實現 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- 指定串連資料庫的驅動 --> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <!-- 指定串連資料庫的URL --> <property name="jdbcUrl" value="jdbc:mysql://localhost/j2ee"/> <!-- 指定串連資料庫的使用者名稱 --> <property name="user" value="root"/> <!-- 指定串連資料庫的密碼 --> <property name="password" value="32147"/> <!-- 指定串連資料庫連接池的最大串連數 --> <property name=&......餘下全文>>
 
spring與hibernate整合

主要是通過Spring管理Hibernate的SessionFactory,Hibernate中的SessionFactory是重量級的線程,而且Spring中提供了對hibernate中dao著了很好的封裝,但初學者可以先自己寫DAO,但是有了一定的基礎的話,用Spring管理DAO或者它自身的DAO,都很好!!Spring對大多ORM架構都有很好的支援,如Ibatis、JPA等等!!

Spring用IOC控制DAO,而且可以用AOP一起和hibernate管理事物!!再實際開發中都非常有用的!!
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.