<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>      

<!-- 要用Spring hibernatetranction管理的話不能要這個-->

<!--        <property name="hibernate.current_session_context_class">thread</property> -->

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

        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

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

       

        <mapping resource="model/CustomerBean.hbm.xml" />

        <mapping resource="model/ProductBean.hbm.xml" />

    </session-factory>

</hibernate-configuration>



<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

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/aop http://www.springframework.org/schema/aop/spring-aop.xsd

    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

 

 

    <bean id="dataSource"

    class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />

        <property name="url"

        value="jdbc:sqlserver://localhost:1433;database=java"></property>

        <property name="username" value="sa"></property>

        <property name="password" value="passw0rd"></property>

    </bean>

    <bean id="sessionFactory" destroy-method="destroy"

    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

        <property name="dataSource" ref="dataSource"></property>

        <property name="configLocation">

        <value>classpath:hibernate.cfg.xml</value>

        </property>

    </bean>

 

    <!-- 設定引入transactionManager,他有一個方法可以setSessionFactory

HibernateTransactionManager中有一個setSessionFactory(SessionFactory sessionFactory)方法-->

    <bean id="transactionManager"

    class="org.springframework.orm.hibernate5.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory"></property>

    </bean>

 

    <!-- 加入advice,等於是設定被呼叫時要做甚麼 -->

    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>

            <tx:method name="*" rollback-for="java.lang.Exception" />

            <!-- name指定試用後續設定的方法名稱,例如下面execution(* model.ProductService.*(..))代表所有ProductService中的任何方法

            但若這邊設定set*代表實際上只有方法中的setter會被執行-->

            <!--  The method name(s) with which the transaction attributes are to be associated.

             The wildcard (*) character can be used to associate the same transaction attribute

             settings with a number of methods; for example,'get*', 'handle*', '*Order', 'on*Event' -->

        </tx:attributes>

    </tx:advice>

 

    <aop:config>

        <aop:pointcut expression="execution(* model.ProductService.*(..))"

            id="product1" />

    <!-- 一定要是ProductService裡面的方法,也就是說ProductService中的任何方法被呼叫時,「整個方法沒有出錯的完成」才會commit,不然方法等於未被呼叫

詳細可看下方兩個testUpdate方法 -->

            <!-- ↑設定一個觸發點(product1),事件在execution(* model.ProductService.*(..))時發生

            也就是任何事件如果設定pointcut-ref="product1",就代表他要會在所有model.ProductService的方法被呼叫時發生-->

            <!-- 如果改成(* model.*.*(..))就是任何model底下的class中的任何方法被呼叫時都會執行事件 -->

        <aop:advisor advice-ref="txAdvice" pointcut-ref="product1" />

        <!-- ↑ ProductService中的任何方法被呼叫時,就會執行txAdvice,也就是只要出錯就會rollback-->

    </aop:config>

 

 

 

    <bean id="CustomerDAOHibernate" class="model.dao.CustomerDAOHibernate">

        <constructor-arg ref="sessionFactory"></constructor-arg>

    </bean>

 

    <bean id="CustomerService" class="model.CustomerService">

        <constructor-arg ref="CustomerDAOHibernate"></constructor-arg>

    </bean>

 

    <bean id="ProductDAOHibernate" class="model.dao.ProductDAOHibernate">

        <constructor-arg ref="sessionFactory"></constructor-arg>

    </bean>

 

    <bean id="ProductService" class="model.ProductService">

        <constructor-arg ref="ProductDAOHibernate"></constructor-arg>

    </bean>

 

</beans>




 

package model;

 

import java.util.ArrayList;

import java.util.List;

 

import org.hibernate.SessionFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

//import model.misc.HibernateUtil;

 

public class ProductService {

    private ProductDAO productDao;

    public ProductService(ProductDAO dao) {

        this.productDao = dao;

    }

    public void testUpdate(){

        System.out.println("testUpdate()");

        ProductBean bean1 = new ProductBean();

        bean1.setId(1);

        bean1.setName("QQ");

        bean1.setExpire(200);

        bean1.setMake(new java.util.Date());

        bean1.setPrice(1999);

        this.update(bean1);

       

        ProductBean bean2 = new ProductBean();

        bean2.setId(2);

    bean2.setName("HOHOOOOTTOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");

        bean2.setExpire(300);

        bean2.setMake(new java.util.Date(0));

        bean2.setPrice(1999);

        //故意讓他長度太常失敗,才能觀察rollback

        this.update(bean2);

       

    }

   

    public static void main(String[] args) {

       

        ApplicationContext context = new ClassPathXmlApplicationContext(

                "beans.xml");      

// 因為交易的開始結束已經都交給設定檔處理了,所以這邊就不用了    

// SessionFactory sessionFactory = (SessionFactory) context

//              .getBean("sessionFactory");

        try {

//      sessionFactory.getCurrentSession().beginTransaction();

            ProductService service = (ProductService) context.getBean("ProductService");

            service.testUpdate();

//          List<ProductBean> beans = service.select(null);

//          System.out.println("beans="+beans);

           

//      sessionFactory.getCurrentSession().getTransaction().commit();

        } finally {

            //close這個就不用特別close sessionFactory

            ((ConfigurableApplicationContext) context).close();

        }

    }

    public List<ProductBean> select(ProductBean bean) {

        List<ProductBean> result = null;

        if(bean!=null && bean.getId()!=0) {

            ProductBean temp = productDao.select(bean.getId());

            if(temp!=null) {

                result = new ArrayList<ProductBean>();

                result.add(temp);

            }

        } else {

            result = productDao.select();

        }

        return result;

    }

    public ProductBean insert(ProductBean bean) {

        ProductBean result = null;

        if(bean!=null) {

            result = productDao.insert(bean);

        }

        return result;

    }

    public ProductBean update(ProductBean bean) {

        System.out.println("Update");

        ProductBean result = null;

        if(bean!=null) {

            result = productDao.update(bean.getName(), bean.getPrice(),

                    bean.getMake(), bean.getExpire(), bean.getId());

        }

        return result;

    }

    public boolean delete(ProductBean bean) {

        boolean result = false;

        if(bean!=null) {

            result = productDao.delete(bean.getId());

        }

        return result;

    }

 

}



package model;

 

import org.hibernate.SessionFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Test {

    private ProductService service;

    public void setService(ProductService service) {

        this.service = service;

    }

//

//  public void testUpdate(){

//     

//      System.out.println("testUpdate()");

//      ProductBean bean1 = new ProductBean();

//      bean1.setId(1);

//      bean1.setName("QQ");

//      bean1.setExpire(200);

//      bean1.setMake(new java.util.Date());

//      bean1.setPrice(1999);

//      System.out.println("testUpdate()");

//      service.update(bean1);

//

//      ProductBean bean2 = new ProductBean();

//      bean2.setId(2);

//  bean2.setName("TEETEETEETEETEETEETEETEETEETEETEETEETEE");

//      bean2.setExpire(300);

//      bean2.setMake(new java.util.Date(0));

//      bean2.setPrice(1999);

//      service.update(bean2);

//  }

 

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext(

                "beans.xml");      

//      SessionFactorybeginTransaction()commit()都交給Spring負責啦,所以這邊刪掉

//      SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");

        try {

//      sessionFactory.getCurrentSession().beginTransaction();

            ProductService service = (ProductService) context.getBean("ProductService");

           

//          Test test = new Test();

//          test.setService(service);

//          test.testUpdate();
//            上面是呼叫test中的testUpdate(),不被監控沒有一起commit的效果

            service.testUpdate();

           

//      sessionFactory.getCurrentSession().getTransaction().commit();

        } finally {

            ((ConfigurableApplicationContext) context).close();

        }

 

    }

 

}

 

arrow
arrow
    全站熱搜

    乙方 發表在 痞客邦 留言(0) 人氣()