Spring4.3.8學(xué)習(xí)之與Hibernate4 整合[五]

如果轉(zhuǎn)載文章請注明出處, 謝謝 !
本系列文章是學(xué)習(xí)完 Spring4.3.8 后的詳細(xì)整理, 如果有錯(cuò)誤請向我指明, 我會(huì)及時(shí)更正~??

Spring4.3.8

Spring4.3.8學(xué)習(xí)[一]
Spring4.3.8學(xué)習(xí)[二]
Spring4.3.8學(xué)習(xí)[三]
Spring4.3.8學(xué)習(xí)之 與 Struts2 整合[四]

6. Spring 與 Hibernate 整合

Spring整合Hibernate有什么好處?
  1、由IoC容器來管理Hibernate的SessionFactory
  2、讓Hibernate使用Spring的聲明式事務(wù)
  
事務(wù): 作為切面 spring 容器
通知: 關(guān)于事務(wù)的操作
開啟事務(wù), 事務(wù)提交, 事務(wù)回滾
目標(biāo)類: service 類
目標(biāo)方法: service 的方法
代理對象代理方法: 目標(biāo)方法+事務(wù)

步驟

  1. 創(chuàng)建持久化類, 映射文件
  2. 在 spring 中引入 sessionFactory[其中有 datasource]
  3. 創(chuàng)建 dao/daoImpl , service/serviceImpl, 將 dao,service 寫入 spring 中
  4. spring 事務(wù)配置 aop

[1] 創(chuàng)建持久化類, 映射文件

public class Person implements Serializable{
    private Long pid;
    private String name;
    private String des; 

    @Override
    public String toString() {
        return "Person{" +
                "pid=" + pid +
                ", name='" + name + '\'' +
                ", des='" + des + '\'' +
                '}';
    }
    public Person() {
    }

    public Person(Long pid, String name, String des) {
        this.pid = pid;
        this.name = name;
        this.des = des;
    }

    public Long getPid() {
        return pid;
    }

    public void setPid(Long pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }
}

----------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.lanou.domain.Person">
        
        <id name="pid" column="pid" length="5">
            <generator class="native"></generator>
        </id>
        
        <property name="name" length="20"/>
        <property name="des" length="50"/>
    </class>
</hibernate-mapping>

[2] 在 spring 中引入 sessionFactory
[其中 datasource 使用c3p0 (別忘了添加 c3p0 和 mySql jar 包)]
將四大參數(shù)配置到 properties 中

jdbc.driver_class=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java1
jdbc.username=root
jdbc.password=123456

配置 datasource:

<!-- 引入 properties 的配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:jdbc.properties"/>
</bean>

<!-- 配置 c3p0 連接 -->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driver_class}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

配置sessionFactory:
第一種方式添加 hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 連接數(shù)據(jù)庫的驅(qū)動(dòng) [datasource 中c3p0配置過了]  -->
        <!--<property name="connection.driver_class">com.mysql.jdbc.Driver</property>-->
        <!--<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>-->
        <!--<property name="connection.username">root</property>-->
        <!--<property name="connection.password">123456</property>-->

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">update</property>

        <property name="current_session_context_class">thread</property>
        <!-- 格式化 sql 語句 -->
        <property name="format_sql">true</property>

        <mapping resource="com/lanou/domain/Person.hbm.xml"/>

    </session-factory>
</hibernate-configuration>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="datasource"/>
    <property name="configLocation">
    <value>classpath:hibernate.cfg.xml</value>
    </property>
</bean>

第二種方式: 不需要hibernate.cfg.xml, 在sessionFactory中直接配置:

<!-- 配置SessionFactory -->
<bean id="sessionFactory2" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="datasource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="show_sql">true</prop>
            <prop key="format_sql">true</prop>
            <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>
    <!-- //加載實(shí)體類的映射文件位置及名稱 -->
    <property name="mappingLocations" value="classpath:com/lanou/domain/*.hbm.xml"></property>
</bean>

[4] 創(chuàng)建 dao/daoImpl , service/serviceImpl, 將 dao,service 寫入 spring 中

public class PersonServiceImpl implements PersonService {
    private PersonDao dao;

    @Override
    public void register(Person person) {
        dao.addPerson(person);
    }

    public PersonDao getDao() {
        return dao;
    }

    public void setDao(PersonDao dao) {
        this.dao = dao;
    }
}
public class PersonDaoImpl implements PersonDao {

    private SessionFactory sessionFactory;
    // 獲得當(dāng)前線程的 session
    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void addPerson(Person person) {
        System.out.println("add .. ");
        getSession().save(person);
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
<bean name="personDao" class="com.lanou.dao.impl.PersonDaoImpl">
    <property name="sessionFactory" ref="sessionFactory2"/>
</bean>

<bean name="personService" class="com.lanou.service.impl.PersonServiceImpl">
    <property name="dao" ref="personDao"/>
</bean>

[5] spring 事務(wù)配置 aop
事務(wù)切面類由 spring 提供, 我們不需要配置

<!-- 事務(wù)的聲明 -->
<!-- 1. 事務(wù)管理器-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory2"></property>
</bean>

<!-- 2. 配置事務(wù), 事務(wù)屬性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!--
        name: 目標(biāo)方法的范圍
        isolation: 隔離機(jī)制 [不同隔離機(jī)制防止臟讀,幻讀]
        propagation: 傳播屬性
        read-only = true是只讀事務(wù),
            false 是讀寫事務(wù)-->
        <tx:method name="add*"/>
            <tx:method name="update*"/>
            <tx:method name="delete*"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" read-only="true"/>
    </tx:attributes>
</tx:advice>

<!-- 配置事務(wù)切點(diǎn),并把切點(diǎn)和事務(wù)屬性關(guān)聯(lián)起來 -->
<!--AOP的配置 -->
<aop:config>
    <!-- 目標(biāo)類: service -->
    <!-- 定義切入點(diǎn),指定切入點(diǎn)表達(dá)式 -->
    <aop:pointcut
            expression="execution(* com.lanou.service.impl.*.*(..))" id="txPointcut"/>
    <!-- 通知設(shè)置-->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>

Spring4.3.8學(xué)習(xí)之S2SH 整合[六]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容