zoukankan      html  css  js  c++  java
  • zbb20170303_spring4_hibernate4事务管理

    1、总体结构图

    2、class

    BookDao.java

    package com.zbb.dao;

    import com.zbb.entity.Book;

    public interface BookDao
    {
    public String findBookById(int id);

    public void saveBook(Book book);
    }

    BookDaoImp.java

    package com.zbb.daoimp;
    
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.zbb.dao.BookDao;
    import com.zbb.entity.Book;
    
    @Repository
    @Transactional
    public class BookDaoImp implements BookDao
    {
        @Autowired
        private SessionFactory sessionFactory;
        
        //获取和当前线程绑定的Seesion
        private Session getSession()
        {
            return sessionFactory.getCurrentSession();
        }
        public String findBookById(int id)
        {
            String hql="SELECT bookName from Book where id=?";
            Query query=getSession().createQuery(hql).setInteger(0, id);
            String str= query.uniqueResult().toString();
            return str;
        }
        public void saveBook(Book book)
        {
            getSession().save(book);
        }
    }

    Book.java

    package com.zbb.entity;
    
    /**
     * Book entity. @author MyEclipse Persistence Tools
     */
    
    public class Book implements java.io.Serializable {
    
        // Fields
    
        private Integer id;
        private String bookName;
        private String isbn;
        private Integer price;
        private Integer stock;
    
        // Constructors
    
        /** default constructor */
        public Book() {
        }
    
        /** full constructor */
        public Book(String bookName, String isbn, Integer price, Integer stock) {
            this.bookName = bookName;
            this.isbn = isbn;
            this.price = price;
            this.stock = stock;
        }
    
        // Property accessors
    
        public Integer getId() {
            return this.id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getBookName() {
            return this.bookName;
        }
    
        public void setBookName(String bookName) {
            this.bookName = bookName;
        }
    
        public String getIsbn() {
            return this.isbn;
        }
    
        public void setIsbn(String isbn) {
            this.isbn = isbn;
        }
    
        public Integer getPrice() {
            return this.price;
        }
    
        public void setPrice(Integer price) {
            this.price = price;
        }
    
        public Integer getStock() {
            return this.stock;
        }
    
        public void setStock(Integer stock) {
            this.stock = stock;
        }
    
    }

    //注解方式entity 选择一种即可
    //package com.zbb.entity; // //import javax.persistence.Column; //import javax.persistence.Entity; //import javax.persistence.GeneratedValue; //import static javax.persistence.GenerationType.IDENTITY; //import javax.persistence.Id; //import javax.persistence.Table; // ///** // * Book entity. @author MyEclipse Persistence Tools // */ //@Entity //@Table(name = "book", catalog = "test") //public class Book implements java.io.Serializable { // // // Fields // // private Integer id; // private String bookName; // private String isbn; // private Integer price; // private Integer stock; // // // Constructors // // /** default constructor */ // public Book() { // } // // /** full constructor */ // public Book(String bookName, String isbn, Integer price, Integer stock) { // this.bookName = bookName; // this.isbn = isbn; // this.price = price; // this.stock = stock; // } // // // Property accessors // @Id // @GeneratedValue(strategy = IDENTITY) // @Column(name = "id", unique = true, nullable = false) // public Integer getId() { // return this.id; // } // // public void setId(Integer id) { // this.id = id; // } // // @Column(name = "book_name", length = 111) // public String getBookName() { // return this.bookName; // } // // public void setBookName(String bookName) { // this.bookName = bookName; // } // // @Column(name = "isbn", length = 111) // public String getIsbn() { // return this.isbn; // } // // public void setIsbn(String isbn) { // this.isbn = isbn; // } // // @Column(name = "price") // public Integer getPrice() { // return this.price; // } // // public void setPrice(Integer price) { // this.price = price; // } // // @Column(name = "stock") // public Integer getStock() { // return this.stock; // } // // public void setStock(Integer stock) { // this.stock = stock; // } // //}

    BookService.java

    package com.zbb.service;
    
    import com.zbb.entity.Book;
    
    public interface BookService
    {
        public String findBookById(int id);
        public void saveBook(Book book);
    }

    BookServiceImp.java

    package com.zbb.serviceimp;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.zbb.dao.BookDao;
    import com.zbb.entity.Book;
    import com.zbb.service.BookService;
    
    @Service
    public class BookServiceImp implements BookService
    {
        @Autowired
        private BookDao bookDao;
        public String findBookById(int id)
        {
            return bookDao.findBookById(id);
        }
        public void saveBook(Book book)
        {
            bookDao.saveBook(book);
            
        }
    }

    MyTest.java

    package com.zbb.test;
    
    import javax.sql.DataSource;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.zbb.entity.Book;
    import com.zbb.service.BookService;
    
    public class MyTest
    {
        private ApplicationContext context=null;
        private BookService bookService=null;
        
        {
             context= new ClassPathXmlApplicationContext("applicationContext.xml");  
             bookService=context.getBean(BookService.class);
        }
        @Test
        public void test()
        {
            DataSource dataSource=(DataSource) context.getBean(DataSource.class);
            System.out.println(dataSource);
        }
        @Test
        public void test2()
        {
            String bookName=bookService.findBookById(1);
            System.out.println(bookName);
        }
        
        @Test
        public void test3()
        {
            bookService.saveBook(new Book("android源码分析", "1002", 45, 10));
        }
    }

    3、xml

    Book.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- 
        Mapping file autogenerated by MyEclipse Persistence Tools
    -->
    <hibernate-mapping>
        <class name="com.zbb.entity.Book" table="book" catalog="test">
            <id name="id" type="java.lang.Integer">
                <column name="id" />
                <generator class="identity" />
            </id>
            <property name="bookName" type="java.lang.String">
                <column name="book_name" length="111" />
            </property>
            <property name="isbn" type="java.lang.String">
                <column name="isbn" length="111" />
            </property>
            <property name="price" type="java.lang.Integer">
                <column name="price" />
            </property>
            <property name="stock" type="java.lang.Integer">
                <column name="stock" />
            </property>
        </class>
    </hibernate-mapping>

    applicationContext.xml

    <?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" xmlns:p="http://www.springframework.org/schema/p"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="		
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd		
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd		
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd		
      http://www.springframework.org/schema/context		
      http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    
    
    	<context:component-scan base-package="com.zbb"></context:component-scan>
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver">
    		</property>
    		<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
    		<property name="username" value="root"></property>
    		<property name="password" value="root"></property>
    	</bean>
    	<bean id="sessionFactory"
    		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    		<property name="dataSource">
    			<ref bean="dataSource" />
    		</property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">
    					org.hibernate.dialect.MySQLDialect
    				</prop>
    				<prop key="hibernate.show_sql">true</prop>
    				<prop key="hibernate.format_sql">true</prop>
    			</props>
    		</property>
    		<!-- .hbm.xml方式配置entity -->
    		
    		<property name="mappingResources">
    			<list>
    				<value>com/zbb/entity/Book.hbm.xml</value>
    			</list>
    		</property>
    		
    		 <!-- 注解方式配置entity -->
    		 <!-- 
    		<property name="annotatedClasses">
    			<list>
    				<value>com.zbb.entity.Book</value>
    			</list>
    		</property>
    		 -->
    	</bean>
    
    	<tx:annotation-driven transaction-manager="transactionManager" />
    	<!-- 配置Spring声明式事务 -->
    	<bean id="transactionManager"
    		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory"></property>
    	</bean>
    	<!-- 配置事务事务属性 -->
    	<tx:advice id="txAdvice" transaction-manager="transactionManager">
    		<tx:attributes>
    			<tx:method name="get*" read-only="true" />
    			<tx:method name="*" />
    		</tx:attributes>
    	</tx:advice>
    	<!-- 配置事务切点,并把切点和事务属性关联起来 -->
    	<aop:config>
    		<aop:pointcut expression="execution(* com.zbb.daoImp.*.*(..))"
    			id="txPointcut" />
    		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
    	</aop:config>
    </beans>

    <?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" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.zbb"></context:component-scan><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property><property name="username" value="root"></property><property name="password" value="root"></property></bean><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource"><ref bean="dataSource" /></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop></props></property><!-- .hbm.xml方式配置entity --><property name="mappingResources"><list><value>com/zbb/entity/Book.hbm.xml</value></list></property> <!-- 注解方式配置entity --> <!-- <property name="annotatedClasses"><list><value>com.zbb.entity.Book</value></list></property> --></bean>
    <tx:annotation-driven transaction-manager="transactionManager" /><!-- 配置Spring声明式事务 --><bean id="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 配置事务事务属性 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="get*" read-only="true" /><tx:method name="*" /></tx:attributes></tx:advice><!-- 配置事务切点,并把切点和事务属性关联起来 --><aop:config><aop:pointcut expression="execution(* com.zbb.daoImp.*.*(..))"id="txPointcut" /><aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /></aop:config></beans>

  • 相关阅读:
    程序员为什么难管理?
    Python多继承
    如何从程序员走向管理层?
    为什么Python能超越JAVA,有什么优势?
    HTTP协议简介与在python中的使用详解
    人力资源管理书籍推荐,这本书HR必看
    把市面上的书翻了个遍,找到这五本经典营销管理书籍推荐给大家
    服务器部署之 cap deploy:setup
    【转】D3DXLoadSkinMeshFromXof函数及.x在不同dx版本中
    【转】C/C++字节对齐算法
  • 原文地址:https://www.cnblogs.com/super-admin/p/6498666.html
Copyright © 2011-2022 走看看