首页 > 编程语言 >spring jdbc 编程式事务

spring jdbc 编程式事务

时间:2023-04-26 22:03:22浏览次数:41  
标签:jdbc spring 编程 springframework user import org public


所谓编程式事务指的是通过编码方式实现事务,即类似于JDBC编程实现事务管理。


新建maven工程,pom文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>spring-jdbc</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<spring.group>org.springframework</spring.group>
		<spring.version>3.1.1.RELEASE</spring.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>${spring.group}</groupId>
			<artifactId>spring-webmvc-portlet</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.6</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.1.0</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.7.4</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.4</version>
		</dependency>

	</dependencies>
</project>



SQL:

CREATE TABLE TB_USER
(
    ID INTEGER PRIMARY KEY,
    USER_NAME VARCHAR2(20) NOT NULL,
    USER_AGE INTEGER NOT NULL
);




java代码:

package springjdbc;

public interface IUserDao {
	void insertUser(User user);
}



package springjdbc;

public class User {
	private String username;
	private int age;

	public User(String username, int age) {
		this.username = username;
		this.age = age;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}


PlatformTransactionManager

package springjdbc.transactions.programmatic.platform;

import java.sql.Types;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import springjdbc.IUserDao;
import springjdbc.User;

public class UserDao implements IUserDao {

	@Autowired
	private PlatformTransactionManager platformTransactionManager;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public void setPlatformTransactionManager(PlatformTransactionManager platformTransactionManager) {
		this.platformTransactionManager = platformTransactionManager;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void insertUser(User user) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		TransactionStatus status = platformTransactionManager.getTransaction(def);

		String sql = "insert into tb_user (id, user_name, user_age) values (1, ?, ?)";
		Object[] params = new Object[] { user.getUsername(), user.getAge(), };
		int[] types = new int[] { Types.VARCHAR, Types.INTEGER, };
		try {
			jdbcTemplate.update(sql, params, types);
			jdbcTemplate.update(sql, params, types);
			platformTransactionManager.commit(status);
		} catch (DataAccessException e) {
			platformTransactionManager.rollback(status);
			throw e;
		}
	}

}




springjdbc/transactions/programmatic/platformContext.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	<context:annotation-config />
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
		<property name="username" value="HIBERNATE" />
		<property name="password" value="HIBERNATE" />
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean id="userDao" class="springjdbc.transactions.programmatic.platform.UserDao">
	</bean>

</beans>





测试类:


package springjdbc.transactions.programmatic;

import java.util.Random;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import springjdbc.IUserDao;
import springjdbc.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("platformContext.xml")
public class TestPlatform {
	
	@Autowired
	ApplicationContext context;
	
	@Test
	public void test() throws Exception {
		Random random = new Random();
		IUserDao dao = context.getBean("userDao", IUserDao.class);
		int id = random.nextInt(100);
		User user = new User("user" + id, id);
		dao.insertUser(user);
	}

}


运行,会报错,因为ID相同,但是,会回滚,数据库里没有插入数据。


TransactionTemplate

package springjdbc.transactions.programmatic.template;

import java.sql.Types;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import springjdbc.IUserDao;
import springjdbc.User;

public class UserDao implements IUserDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private TransactionTemplate transactionTemplate;

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void insertUser(final User user) {
		transactionTemplate.execute(new TransactionCallback<Integer>() {
			public Integer doInTransaction(TransactionStatus status) {
				String sql = "insert into tb_user (id, user_name, user_age) values (1, ?, ?)";
				Object[] params = new Object[] { user.getUsername(), user.getAge(), };
				int[] types = new int[] { Types.VARCHAR, Types.INTEGER, };
				jdbcTemplate.update(sql, params, types);
				return jdbcTemplate.update(sql, params, types);
			}
		});
	}

}




springjdbc/transactions/programmatic/templateContext.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	<context:annotation-config />
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean id="txTemplate"
		class="org.springframework.transaction.support.TransactionTemplate">
		<property name="transactionManager" ref="transactionManager"></property>
	</bean>
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
		<property name="username" value="HIBERNATE" />
		<property name="password" value="HIBERNATE" />
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean id="userDao" class="springjdbc.transactions.programmatic.template.UserDao">
	</bean>

</beans>




测试类:

package springjdbc.transactions.programmatic;

import java.util.Random;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import springjdbc.IUserDao;
import springjdbc.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("templateContext.xml")
public class TestTemplate {
	
	@Autowired
	ApplicationContext context;
	
	@Test
	public void test() throws Exception {
		Random random = new Random();
		IUserDao dao = context.getBean("userDao", IUserDao.class);
		int id = random.nextInt(100);
		User user = new User("user" + id, id);
		dao.insertUser(user);
	}

}




运行,会报错,因为ID相同,但是,会回滚,数据库里没有插入数据。


标签:jdbc,spring,编程,springframework,user,import,org,public
From: https://blog.51cto.com/u_1002776/6229000

相关文章

  • spring aop 注解方式
    前置、后置、环绕、切面、切点packagecom.springinaction.springidol;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.AfterReturning;importorg.aspectj.lang.annotation.AfterThrowing;importorg.aspectj.lang.annotation.Around;imp......
  • spring aop xml方式
    工程如图:pom文件内容:<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd" xmlns......
  • java 并发编程-基础篇
    java创建线程的三种方法直接使用Thread//创建线程对象Threadt=newThread(){publicvoidrun(){//要执行的任务}};//启动线程t.start();Runable配合Thread把线程和任务分开。Runnablerunnable=newRunnable(){publicvoidrun(......
  • 实验3 控制语句与组合数据类型应用编程
    1。实验任务1task1.py1importrandom23print('用列表储存随机整数:')4lst=[random.randint(0,100)foriinrange(5)]5print(lst)67print('\n用集合储存随机整数:')8s1={random.randint(0,100)foriinrange(5)}9print(s1)1011print(&#......
  • 2023.4.26编程一小时打卡
    一、问题描述:有一元二次方程ax2+bx+c=0,其一般解为x1,2=(-b±b2-4ac)/2a,但若a=0或b2-4ac<0时,用此公式出错。编程序,从键盘输入a,b,c的值,求x1和x2。如果a=0或b2-4ac<0,输出出错信息。二、解题思路:首先,将定义a,b,c为浮点数,然后输入a,b,c,去判断二次项系数的大小是否符合,再去判断b*2......
  • spring jdbc 声明式事务
    Spring的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指在配置文件中申明。用在Spring配置文件中声明式的处理事务来代替代码式的处理事务。这样的好处是,事务管理不侵入开发的组件,具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事......
  • SpringSecurity从入门到精通:认证成功处理器&认证失败处理器
    认证成功处理器  认证失败处理器  ......
  • c语言趣味编程(8)冒泡排序
    一、问题描述对n个整数进行升序排列(数据由键盘键入)二、设计思路(1)读取从键盘键入的n个数据,存入数组a中;(2)用for循环对数组a中的数据进行遍历,并用if语句来判断大小,按从小到大存入;(3)遍历输出数组中已经完成升序排列的数组元素;三、程序流程图 四、伪代码五、代码1#include......
  • java连接jdbc-mssql数据库
    packagecom.swift.erp;importjava.sql.SQLException;importjava.sql.Statement;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;publicclassAPP{//引入sqljdbc.jarpublicstaticvoidmain(String[]args......
  • PVD-CH32可编程电压控制器PVD中断的使用方法
    可编程电压监视器PVD,主要被用于监控系统主电源的变化,与电源控制寄存器PWR_CTLR的PLS[2:0]所设置的门槛电压相比较,配合外部中断寄存器(EXTI)设置,可产生相关中断,以便及时通知系统进行数据保存等掉电前操作。配置方法如下:先使能PWR时钟,然后设置电压监视阈值,随后使能PVDE开......