Spring学习之声明式事务处理实例(DriverManagerDataSource注入)

首先建立helloDao.java用来处理数据

package com.gc.action;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class HelloDao {
	private DataSource dataSource;
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource){
		this.dataSource = dataSource;
		jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public void create(String name){
		String sql ="insert into tb1 values (3,'bv','zs')";
		jdbcTemplate.update(sql);
		System.out.println(name+"^^..^^^^^^^^^^^^^");
	}
}
在配置config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://localhost:3306/mytest1</value>
		</property>
		<property name="username">
			<value>root</value>
		</property>
		<property name="password">
			<value>123</value>
		</property>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref bean="dataSource"/>
		</property>
	</bean>
	<bean id="helloDao" class="com.gc.action.HelloDao">
		<property name="dataSource">
			<ref bean="dataSource"/>
		</property>
	</bean>
	<bean id="helloDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager">
			<ref bean = "transactionManager"/>
		</property>
		<property name="target">
			<ref bean="helloDao"/>
		</property>
		<property name="transactionAttributes">
			<props>
				<prop key="create*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>
	
</beans>

最后建立一个测试类

package com.gc.test;



import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.gc.action.HelloDao;
import com.gc.impl.FinanceInterface;
import com.gc.impl.TimeBookInterface;


public class testExample {

	public static void main(String[] args) throws InstantiationException,IllegalAccessException,
	ClassNotFoundException{
		String path = "D:\\tianWorkPlace\\5_2\\WebContent\\config.xml";
		ApplicationContext actx = new FileSystemXmlApplicationContext(path);
//		FinanceInterface financeProxy = (FinanceInterface) actx.getBean("logProxy");
//		financeProxy.doCheck("李四");
		
		HelloDao hello = (HelloDao) actx.getBean("helloDAOProxy");
		//timeBookProxy.doCheck("zhang San");
		hello.create("zhang san");
	}

}

运行,确实没错,最后mysql数据库表tb1中确实插入了“3,bv,zz"这条记录!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值