声明式事务管理

Posted 初夏的一棵歪脖子树

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了声明式事务管理相关的知识,希望对你有一定的参考价值。

声明事务管理(数据库连接池)

1.dao

 1 package com.zhidi.dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 
 8 import javax.sql.DataSource;
 9 
10 import org.hibernate.Session;
11 import org.hibernate.SessionFactory;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.stereotype.Repository;
14 
15 import com.zhidi.entity.Emp;
16 
17 @Repository
18 public class EmpDao {
19     @Autowired
20     private DataSource dataSource;
21     @Autowired
22     private SessionFactory sessionFactory;
23 
24     public void query() {
25         try {
26             Connection connection = dataSource.getConnection();
27             PreparedStatement statement = connection.prepareStatement("select * from emp");
28             ResultSet set = statement.executeQuery();
29             while (set.next()) {
30                 String name = set.getString("ename");
31                 System.out.println(name);
32             }
33         } catch (SQLException e) {
34             e.printStackTrace();
35         }
36     }
37 
38     public void get(Integer id) {
39         Session session = sessionFactory.getCurrentSession();
40         session.beginTransaction();
41         session.get(Emp.class, id);
42         session.getTransaction().commit();
43     }
44     
45     public Emp getById(Integer id)
46     {
47         Session session = sessionFactory.getCurrentSession();
48         Emp emp=(Emp)session.get(Emp.class, id);
49         return emp;
50     }
51     
52     public void delete(Integer id)
53     {
54        Session session = sessionFactory.getCurrentSession();
55        Emp emp=    getById(id);
56        session.delete(emp);
57        
58     }
59 }
View Code

2.entity

 1 package com.zhidi.entity;
 2 
 3 import java.util.Date;
 4 
 5 import javax.persistence.Entity;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.GenerationType;
 8 import javax.persistence.Id;
 9 import javax.persistence.Table;
10 import javax.persistence.Temporal;
11 import javax.persistence.TemporalType;
12 
13 @Entity
14 @Table(name = "emp")
15 public class Emp {
16     @Id
17     @GeneratedValue(strategy = GenerationType.AUTO)
18     private Integer empno;
19     private String ename;
20     @Temporal(TemporalType.DATE)
21     private Date hiredate;
22 
23     public Integer getEmpno() {
24         return empno;
25     }
26 
27     public void setEmpno(Integer empno) {
28         this.empno = empno;
29     }
30 
31     public String getEname() {
32         return ename;
33     }
34 
35     public void setEname(String ename) {
36         this.ename = ename;
37     }
38 
39     public Date getHiredate() {
40         return hiredate;
41     }
42 
43     public void setHiredate(Date hierdate) {
44         this.hiredate = hierdate;
45     }
46 
47 }
View Code

 

3.service

 1 package com.zhidi.service;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Service;
 5 import org.springframework.transaction.annotation.Propagation;
 6 import org.springframework.transaction.annotation.Transactional;
 7 
 8 import com.zhidi.dao.EmpDao;
 9 import com.zhidi.entity.Emp;
10 @Transactional
11 @Service
12 public class EmpService {
13     @Autowired
14     private EmpDao empDao;
15     @Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
16     public Emp getById(Integer id)
17     {
18         return empDao.getById(id);
19     }
20     
21     public void deleteById(Integer id)
22     {
23         empDao.delete(id);
24     }
25 
26 }
View Code

 

4.test

 1 package com.zhidi.test;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.zhidi.dao.EmpDao;
 7 
 8 public class TestEmp {
 9 
10     public static void main(String[] args) {
11         @SuppressWarnings("resource")
12         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
13         EmpDao empDao = context.getBean(EmpDao.class);
14         empDao.query();
15 
16         empDao.get(7965);
17     }
18 }
View Code
 1 package com.zhidi.test;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.zhidi.entity.Emp;
 7 import com.zhidi.service.EmpService;
 8 
 9 public class TestTx {
10     
11     public static void main(String[] args) {
12         @SuppressWarnings("resource")
13         ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
14         EmpService service=context.getBean(EmpService.class);
15         Emp emp=service.getById(7959);
16         System.out.println(emp.getEname());
17         
18         service.deleteById(7951);
19     
20     }
21 
22 }
View Code

 

5.applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 4     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 6         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
 7         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
 8         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
 9 
10     <!-- 打开配置 -->
11     <!-- <context:component-scan base-package="com.zhidi" /> -->
12     <context:property-placeholder location="jdpc.properties" /> 
13     <!-- 将c3p0交给Spring的IOC容器管理 -->
14     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
15         <!-- 必要的配置 -->
16         <property name="driverClass" value="${jdpc.driverClass}" />
17         <property name="jdbcUrl" value="${jdpc.url}" />
18         <property name="user" value="${jdpc.userName}" />
19         <property name="password" value="${jdpc.password}" />
20         <!-- 初始化连接数 -->
21         <property name="initialPoolSize" value="3" />
22         <!-- 最大连接数 -->
23         <property name="maxPoolSize" value="10" />
24         <!-- 最小连接数 -->
25         <property name="minPoolSize" value="1"></property>
26         <!-- 最大的连接时间8小时 -->
27         <property name="maxConnectionAge" value="28800"></property>
28         <!-- 需要防止8小时陷阱,需要设置时间小于8小时 -->
29         <!-- 设置为6小时 -->
30         <property name="maxIdleTime" value="21600"></property>
31     </bean>
32 
33     <!-- 将LocalSessionFactoryBean交给Spring的IOC容器管理 -->
34     <bean id="sessionFactory"
35         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
36         <!-- 将c3p0的数据源注入到SessionFactory -->
37         <property name="dataSource" ref="dataSource"></property>
38         <!-- 指定hibernate的配置信息 -->
39         <property name="hibernateProperties">
40             <props>
41                 <prop key="hibernate.dialect">org.hibernate.dialect.mysql5Dialect</prop>
42                 <prop key="hibernate.show_sql">true</prop>
43                 <prop key="hibernate.format_sql">true</prop>
44                 <!-- 删掉或者把 thread改为org.springframework.orm.hibernate4.SpringSessionContext-->
45                 <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
46             </props>
47         </property>
48         <!-- 指定扫描@entity的实体类 -->
49         <property name="packagesToScan" value="com.zhidi.entity" />
50     </bean>
51 
52     <!-- 定义hibernate的事务管理 -->
53     <bean id="transactionManager"
54         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
55         <!-- 将sessionFactory注入事务管理器中 -->
56         <property name="sessionFactory" ref="sessionFactory" />
57     </bean>
58     <!-- 开启事务管理的配置 -->
59     <tx:annotation-driven transaction-manager="transactionManager"/>
60     
61     <!-- 配置事务管理 -->
62     <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">
63         为不同的目标方法指定不同的事务属性
64         <tx:attributes>
65             name指定该事务属性对应的方法 propagation指事务的传播特性 read-only只读
66             <tx:method name="add*" propagation="REQUIRED" />
67             <tx:method name="save*" propagation="REQUIRED" />
68             <tx:method name="delete*" propagation="REQUIRED" />
69             <tx:method name="modeif*" propagation="REQUIRED" />
70             <tx:method name="update*" propagation="REQUIRED" />
71             <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
72             <tx:method name="query*" propagation="SUPPORTS" read-only="true" />
73             <tx:method name="search*" propagation="SUPPORTS" read-only="true" />
74             <tx:method name="*" propagation="SUPPORTS" read-only="true" />
75         </tx:attributes>
76     </tx:advice> -->
77     
78     <!-- 定义事务处理的AOP切面 -->
79      <aop:config>
80         <aop:advisor advice-ref="txAdvice"
81             pointcut="execution(* com.zhidi.service..*.*(..))" />
82     </aop:config> 
83 
84 </beans>
View Code

 

6.properties

1 jdpc.driverClass=com.mysql.jdbc.Driver
2 jdpc.url=jdbc:mysql://localhost:3306/db_hibernate
3 jdpc.userName=root
4 jdpc.password=775297
View Code
 1 ### direct log messages to stdout ###
 2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 3 log4j.appender.stdout.Target=System.out
 4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 5 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 6 
 7 ### direct messages to file hibernate.log ###
 8 #log4j.appender.file=org.apache.log4j.FileAppender
 9 #log4j.appender.file.File=hibernate.log
10 #log4j.appender.file.layout=org.apache.log4j.PatternLayout
11 #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
12 
13 ### set log levels - for more verbose logging change \'info\' to \'debug\' ###
14 
15 log4j.rootLogger=warn, stdout
16 
17 #log4j.logger.org.hibernate=info
18 log4j.logger.org.hibernate=debug
19 
20 ### log HQL query parser activity
21 #log4j.logger.org.hibernate.hql.ast.AST=debug
22 
23 ### log just the SQL
24 #log4j.logger.org.hibernate.SQL=debug
25 
26 ### log JDBC bind parameters ###
27 log4j.logger.org.hibernate.type=info
28 #log4j.logger.org.hibernate.type=debug
29 
30 ### log schema export/update ###
31 log4j.logger.org.hibernate.tool.hbm2ddl=debug
32 
33 ### log HQL parse trees
34 #log4j.logger.org.hibernate.hql=debug
35 
36 ### log cache activity ###
37 #log4j.logger.org.hibernate.cache=debug
38 
39 ### log transaction activity
40 #log4j.logger.org.hibernate.transaction=debug
41 
42 ### log JDBC resource acquisition
43 #log4j.logger.org.hibernate.jdbc=debug
44 
45 ### enable the following line if you want to track down connection ###
46 ### leakages when using DriverManagerConnectionProvider ###
47 #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
View Code

 

以上是关于声明式事务管理的主要内容,如果未能解决你的问题,请参考以下文章

spring学习笔记声明式事务

Spring针对事务处理提供哪两种事务编程模式。

Spring声明式事务管理

9.spring:事务管理(下):声明式事务管理

使用SpringAOP实现事务(声明式事务管理零配置)

项目一众筹网01_03环境搭建_声明式事务