首先建立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"这条记录!!!