注意使用Annotation時每個類別都要做一個空的建構子!!!

 

<?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 hibernate4tranction管理的話不能要這個,但5的話要-->

<!--        <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: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-4.2.xsd

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

    <bean id="transactionManager"

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

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

    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <context:annotation-config></context:annotation-config>

    <context:component-scan base-package="model"></context:component-scan>

    <!-- 不在需要做DAOServer的設定了, annotation-->

<!-- 注意測試時雖然適用productServer來測試,但是customer中也要有無參數建構子-->

</beans>



package model.dao;

 

import java.util.Date;

import java.util.List;

 

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.stereotype.Repository;

 

import model.ProductBean;

import model.ProductDAO;

 

//import model.misc.HibernateUtil;

@Transactional(transactionManager="transactionManager")

@Repository("productDao")

public class ProductDAOHibernate implements ProductDAO {

    @Autowired

    private SessionFactory sessionFactory = null;

    public ProductDAOHibernate() {

       

    }

   

    public ProductDAOHibernate(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;

    }

 

   

    public Session getSession() {

        return sessionFactory.getCurrentSession();

    }

 

    @Override

    public ProductBean select(int id) {

        return (ProductBean) this.getSession().get(ProductBean.class, id);

    }

 

    @Override

    public List<ProductBean> select() {

        Query query = this.getSession().createQuery("from ProductBean");

        return (List<ProductBean>) query.list();

    }

 

    @Override

    public ProductBean insert(ProductBean bean) {

        ProductBean result = (ProductBean) this.getSession().get(

                ProductBean.class, bean.getId());

        if (result == null) {

            this.getSession().save(bean);

            return bean;

        }

        return null;

    }

 

    @Override

    public ProductBean update(String name, double price, Date make, int expire,

            int id) {

        ProductBean result = (ProductBean) this.getSession().get(

                ProductBean.class, id);

        if (result != null) {

            result.setName(name);

            result.setPrice(price);

            result.setMake(make);

            result.setExpire(expire);

        }

        return result;

    }

 

    @Override

    public boolean delete(int id) {

        ProductBean bean = (ProductBean) this.getSession().get(

                ProductBean.class, id);

        if (bean != null) {

            this.getSession().delete(bean);

            return true;

        }

        return false;

    }

}



package model;

 

import java.util.ArrayList;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

 

@Service("productService")

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

//@Transactional(transactionManager = "transactionManager")

// 也可以放在DAO

public class ProductService {

    @Transactional

    public void testUpdate() {

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

        ProductBean bean1 = new ProductBean();

        bean1.setId(1);

        bean1.setName("AQ");

        bean1.setExpire(200);

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

        bean1.setPrice(1999);

        this.update(bean1);

 

        ProductBean bean2 = new ProductBean();

        bean2.setId(2);

        bean2.setName("AAOOOOO");

        bean2.setExpire(300);

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

        bean2.setPrice(1999);

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

        this.update(bean2);

 

    }

    @Autowired

    private ProductDAO productDao;

 

    public ProductService(ProductDAO dao) {

        this.productDao = dao;

    }

    public ProductService() {

    }

 

    public static void main(String[] args) {

 

        ApplicationContext context = new ClassPathXmlApplicationContext(

                "annotation.beans.xml");

        try {

            ProductService service = (ProductService) context

                    .getBean("productService");

            service.testUpdate();

        } finally {

            ((ConfigurableApplicationContext) context).close();

        }

    }

 

    @Transactional(readOnly = true)

    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;

    }

 

    @Transactional

    public ProductBean insert(ProductBean bean) {

        ProductBean result = null;

        if (bean != null) {

            result = productDao.insert(bean);

        }

        return result;

    }

 

    @Transactional

    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;

    }

 

    @Transactional

    public boolean delete(ProductBean bean) {

        boolean result = false;

        if (bean != null) {

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

        }

        return result;

    }

 

}





如果要用DAO來做@annotation,必須要用interface來接!!!

package test;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import model.ProductDAO;

import model.dao.ProductDAOHibernate;

 

public class TestAnnotation {

    private ProductDAO productDAOHibernate;

    public void setProductDAOHibernate(ProductDAO productDAOHibernate) {

    this.productDAOHibernate = productDAOHibernate;

}

    public void testUpdate() {

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

       productDAOHibernate.update("hehehe",123,new java.util.Date(),200,9);

       productDAOHibernate.update("hehehe",123,new java.util.Date(),200,10);

    }

    public static void main(String[] args) {

       ApplicationContext context =

              new ClassPathXmlApplicationContext("annotation.config.xml");

       try {

           ProductDAO productDAOHibernate =(ProductDAO)context.getBean("productDao");

           TestAnnotation test = new TestAnnotation();

           test.setProductDAOHibernate(productDAOHibernate);

           test.testUpdate();

       } finally {

           ((ConfigurableApplicationContext) context).close();

       }

    }

}

 

創作者介紹

學習筆記專區

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