第一步:(在applicationContext.xml中配置数据源)
......
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>oracle.jdbc.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:orcl</value>
</property>
<property name="username">
<value>system</value>
</property>
<property name="password">
<value>abcd</value>
</property>
</bean>
......
注意:定义新事件有两种方法,本文先只介绍其中的一种,另外一种在(二)文章中
第二步:(利用DataSourceTransactionManager产生一个新的事物,新事物用DefaultTransactionDefinition定义属性)
import javax.sql.DataSource;(接口)
import org.springframework.context.support.ClassPathXmlApplicationCotext;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;(接口)
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
..................
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource ds=(DataSource)ac.getBean("dataSource");
DataSourceTransactionManager transactionManager=new DataSourceTransactionManager(ds);
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
jdbcTemplate.update("INSERT INTO table1 VALUES('Spring008','caterpillar')");
jdbcTemplate.update("INSERT INTO table1 VALUES('Spring009','momor')");
jdbcTemplate.update("INSERT INTO table1 VALUES('Spring010','beckyday')");
} catch (DataAccessException ex) {
transactionManager.rollback(status);
throw ex;
}
if(status.isCompleted()) out.println("事物完成");
else out.println("事物未完成");
transactionManager.commit(status);
if(status.isCompleted()) out.println("事物完成");
else out.println("事物未完成");
..................
输出结果:
This is my JSP page.
事物未完成事物完成
//至于事件什么时候结束大家都看到了吧,呵呵,如果想看其他属性,自己测试吧