08 配置方式完成事务
程序员文章站
2022-03-23 17:04:31
...
上一节我们了解了通过注解方式使用,这一节我们了解一下基于注解的事务。
1、前提约束
- 完成jdbctemplate的使用 https://www.jianshu.com/p/57f470899442
2、操作步骤
- 确保在application.xml中包含以下内容:
<bean id="userService" class="net.wanho.service.UserService">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="zhangli"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
<property name="dataSource" ref="datasource"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<tx:advice id="advice">
<tx:attributes>
<tx:method name="add*" read-only="false" rollback-for="Exception"/>
<tx:method name="delete*" read-only="false" rollback-for="Exception"/>
<tx:method name="update*" read-only="false" rollback-for="Exception"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pt" expression="execution(* net.wanho.service.*.*(..))"/>
<aop:advisor advice-ref="advice" pointcut-ref="pt"></aop:advisor>
</aop:config>
- 在src/main/java文件下创建net.wanho.service.UserService.java,内容如下:
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
public class UserService {
private JdbcTemplate jdbcTemplate;
public void addUser()
{
jdbcTemplate.update("insert into t_user(id,name) values(?,?)",new Object[]{1,"jiangsu"});
System.out.println(1 / 0);
jdbcTemplate.update("insert into t_user(id,name) values(?,?)",new Object[]{2,"wanhe"});
}
public void addUser1()
{
jdbcTemplate.update("insert into t_user(id,name) values(?,?)",new Object[]{3,"wanho"});
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
- 在src/main/java文件下创建Test.java,内容如下:
public class Test{
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
UserService userService = applicationContext.getBean("userService",UserService.class);
userService.addUser();
userService.addUser1();
}
}
以上就是在springaop中通过配置方式完成事务控制。
上一篇: Python3面向对象——案例-01