您的位置:首页 > 编程语言 > Java开发

spring 注解事务机制配置和xml事务配置

2014-09-16 15:21 281 查看
-----------------------------注解方式事务配置:------------------------

建表语句

create table person(

id int not null primary key ,

name varchar(20) not null

)

建立自增长序号

CREATE SEQUENCE seq_person start with 1 increment by 1

jdbc.properties文件

driverClassName=oracle.jdbc.driver.OracleDriver

url=jdbc:oracle:thin:@192.168.1.123:1521:orcl2

username=gsjg

password=gsjg

initialSize=1

maxActive=500

maxIdle=100

minIdle=1

<?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: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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop href="http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" target=_blank>http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx href="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" target=_blank>http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<context:property-placeholder location="classpath:jdbc.properties" />

<bean id="dataSource"

class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close">

<property name="driverClassName" value="${driverClassName}" />

<property name="url" value="${url}" />

<property name="username" value="${username}" />

<property name="password" value="${password}" />

<!-- 连接池启动时的初始值 -->

<property name="initialSize" value="${initialSize}" />

<!-- 连接池的最大值 -->

<property name="maxActive" value="${maxActive}" />

<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

<property name="maxIdle" value="${maxIdle}" />

<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

<property name="minIdle" value="${minIdle}" />

</bean>

<bean id="personService"

class="com.royzhou.jdbc.PersonServiceImpl">

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

</bean>

<bean id="txManager"

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

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

</bean>

<!-- 注册激活注解方式事物机制 -->

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

</beans>

package com.royzhou.jdbc;

public class PersonBean {

private int id;

private String name;

public PersonBean() {

}

public PersonBean(String name) {

this.name = name;

}

public PersonBean(int id, String name) {

this.id = id;

this.name = name;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String toString() {

return this.id + ":" + this.name;

}

}

package com.royzhou.jdbc;

import java.sql.ResultSet;

import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

public class PersonRowMapper implements RowMapper {

//默认已经执行rs.next(),可以直接取数据

public Object mapRow(ResultSet rs, int index) throws SQLException {

PersonBean pb = new PersonBean(rs.getInt("id"),rs.getString("name"));

return pb;

}

}

package com.royzhou.jdbc;

import java.util.List;

public interface PersonService {

public void addPerson(PersonBean person) throws Exception;

public void updatePerson(PersonBean person);

public void deletePerson(int id);

public PersonBean queryPerson(int id);

public List<PersonBean> queryPersons();

}

package com.royzhou.jdbc;

import java.sql.Types;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.transaction.annotation.Transactional;

@Transactional

public class PersonServiceImpl implements PersonService {

private JdbcTemplate jdbcTemplate;

/**

* 通过Spring容器注入datasource

* 实例化JdbcTemplate,该类为主要操作数据库的类

* @param ds

*/

public void setDataSource(DataSource ds) {

this.jdbcTemplate = new JdbcTemplate(ds);

}

//@Transactional(noRollbackFor=RuntimeException.class)打开可以指定默认异常,事物不回滚

//@Transactional(rollbackFor=Exception.class) 打开可以指定特定异常,事物回滚

public void addPerson(PersonBean person) throws Exception {

/**

* 第一个参数为执行sql

* 第二个参数为参数数据

* 第三个参数为参数类型

*/

jdbcTemplate.update("insert into person values(seq_person.nextval,?)", new Object[]{person.getName()}, new int[]{Types.VARCHAR});

throw new RuntimeException("运行期异常支持事务回滚");

//throw new Exception("其他异常不支持事务回滚");



}

public void deletePerson(int id) {

jdbcTemplate.update("delete from person where id = ?", new Object[]{id}, new int[]{Types.INTEGER});

}

@SuppressWarnings("unchecked")

public PersonBean queryPerson(int id) {

/**

* new PersonRowMapper()是一个实现RowMapper接口的类,

* 执行回调,实现mapRow()方法将rs对象转换成PersonBean对象返回

*/

List<PersonBean> pbs = (List<PersonBean>)jdbcTemplate.query("select id,name from person where id = ?", new Object[]{id}, new PersonRowMapper());

PersonBean pb = null;

if(pbs.size()>0) {

pb = pbs.get(0);

}

return pb;

}

@SuppressWarnings("unchecked")

public List<PersonBean> queryPersons() {

List<PersonBean> pbs = (List<PersonBean>) jdbcTemplate.query("select id,name from person", new PersonRowMapper());

return pbs;

}

public void updatePerson(PersonBean person) {

jdbcTemplate.update("update person set name = ? where id = ?", new Object[]{person.getName(), person.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});

}

}

对于一些查询方法,因为不需要配置事务支持,我们配置事务的传播属性:

@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)

readOnly=true表示事务中不允许存在更新操作.



package com.royzhou.jdbc;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestJdbcTemplate {

public static void main(String[] args) throws Exception {

ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-sqlserver.xml");

PersonService ps = (PersonService)ctx.getBean("personService");

ps.addPerson(new PersonBean("royzhou"));

//PersonBean pb = ps.queryPerson(1);

//System.out.println(pb);

//pb.setName("haha");

//ps.updatePerson(pb);

/*pb = ps.queryPerson(1);

System.out.println(pb);

ps.deletePerson(1);

pb = ps.queryPerson(1);

System.out.println(pb);*/

}

}

-----------------------------------------------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:context="http://www.springframework.org/schema/context"

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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop href="http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" target=_blank>http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx href="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" target=_blank>http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<context:property-placeholder location="classpath:jdbc.properties" />

<bean id="dataSource"

class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close">

<property name="driverClassName" value="${driverClassName}" />

<property name="url" value="${url}" />

<property name="username" value="${username}" />

<property name="password" value="${password}" />

<!-- 连接池启动时的初始值 -->

<property name="initialSize" value="${initialSize}" />

<!-- 连接池的最大值 -->

<property name="maxActive" value="${maxActive}" />

<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

<property name="maxIdle" value="${maxIdle}" />

<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

<property name="minIdle" value="${minIdle}" />

</bean>

<bean id="personService"

class="com.royzhou.jdbc.PersonServiceImpl">

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

</bean>

<bean id="txManager"

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

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

</bean>

<!-- 定义事务传播属性XML配置 -->

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

<tx:attributes>

<tx:method name="query*" propagation="NOT_SUPPORTED" read-only="true"/>

<tx:method name="*" propagation="REQUIRED"/>

</tx:attributes>

</tx:advice>

<aop:config>

<aop:pointcut id="transactionPointCut" expression="execution(* com.royzhou.jdbc..*.*(..))"/>

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

</aop:config>

</beans>

REQUIRED:业务方法需要在一个事务中运行,如果方法运行时,已经处于一个事务中,那么加入到该事务中,否则自己创建一个新的事务.(Spring默认的事务传播属性)

NOT_SUPPORTED:声明方法不需要事务,如果方法没有关联到一个事务,容器不会为它开启事务,如果方法在一个事务中被调用,该事务被挂起,在方法调用结束后,原先的事务便会恢复执行


package com.royzhou.jdbc;

import java.sql.Types;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class PersonServiceImpl implements PersonService {

private JdbcTemplate jdbcTemplate;

/**

* 通过Spring容器注入datasource

* 实例化JdbcTemplate,该类为主要操作数据库的类

* @param ds

*/

public void setDataSource(DataSource ds) {

this.jdbcTemplate = new JdbcTemplate(ds);

}

public void addPerson(PersonBean person) throws Exception {

/**

* 第一个参数为执行sql

* 第二个参数为参数数据

* 第三个参数为参数类型

*/

jdbcTemplate.update("insert into person values(seq_person.nextval,?)", new Object[]{person.getName()}, new int[]{Types.VARCHAR});

//throw new RuntimeException("运行期异常支持事务回滚");

throw new Exception("其他异常不支持事务回滚");

}

public void deletePerson(int id) {

jdbcTemplate.update("delete from person where id = ?", new Object[]{id}, new int[]{Types.INTEGER});

}

@SuppressWarnings("unchecked")

public PersonBean queryPerson(int id) {

/**

* new PersonRowMapper()是一个实现RowMapper接口的类,

* 执行回调,实现mapRow()方法将rs对象转换成PersonBean对象返回

*/

List<PersonBean> pbs = (List<PersonBean>)jdbcTemplate.query("select id,name from person where id = ?", new Object[]{id}, new PersonRowMapper());

PersonBean pb = null;

if(pbs.size()>0) {

pb = pbs.get(0);

}

return pb;

}

@SuppressWarnings("unchecked")

public List<PersonBean> queryPersons() {

List<PersonBean> pbs = (List<PersonBean>) jdbcTemplate.query("select id,name from person", new PersonRowMapper());

return pbs;

}

public void updatePerson(PersonBean person) {

jdbcTemplate.update("update person set name = ? where id = ?", new Object[]{person.getName(), person.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: