我有两个春季服务。非事务性的Service1.foo()调用Service2.bar()是事务性的。所以我想知道我的交易是否仅限于service2.bar()。我想确保Service1.foo()不在事务中运行。我的代码是否正确?
class Service1
{
public void foo() {
//some non transaction code
service2.bar();
//some non transaction code
}
}
@Transactional
class Service2
{
public void bar() {
//TODO;
}
}
答案 0 :(得分:0)
是。 如果你正确设置了事务支持并且你正在使用@Transactional的正确导入(org.springframework.transaction.annotation.Transactional
),那么只有Service2中的方法在一个事务中运行,而Service1中的方法没有
如果设置不正确,则事务中不会运行任何内容。
答案 1 :(得分:0)
是的,您的代码适用于您提到的方案。请参阅下面的代码示例,执行后,只有1条记录插入TEST_TABLE,CD = INSERT3。我在Dao2impl中插入了错误的列,以使事务失败。
下面是Service1类,我调用的是insertMainServiceCall方法,该方法调用insertData方法,需要在事务中执行:
@Service
public class Service1 {
@Autowired
private Service2 service2;
@Autowired
private DataSource datasource;
private JdbcTemplate jdbcTemplate;
public Service2 getService2() {
return service2;
}
public void setService2(Service2 service2) {
this.service2 = service2;
}
public DataSource getDatasource() {
return datasource;
}
public void setDatasource(DataSource datasource) {
this.datasource = datasource;
}
public void insertMainServiceCall(){
String sqlCmd="INSERT INTO TEST_TABLE " +
"(CD, NAME, DEPT) VALUES (?, ?, ?)";
jdbcTemplate = new JdbcTemplate(datasource);
jdbcTemplate.update(sqlCmd, new Object[] {"INSERT3",
"INSERT3","INSERT3"
});
service2.insertData();
}
}
以下是我的Service2课程:
@Transactional
@Service
public class Service2 {
@Autowired
private Dao1 dao1;
@Autowired
private Dao2 dao2;
public Dao1 getDao1() {
return dao1;
}
public void setDao1(Dao1 dao1) {
this.dao1 = dao1;
}
public Dao2 getDao2() {
return dao2;
}
public void setDao2(Dao2 dao2) {
this.dao2 = dao2;
}
public void insertData(){
dao1.insert1();
dao2.insert2();
}
}
下面是我的Dao1Impl类代码:
@Repository
public class Dao1Impl implements Dao1{
@Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void insert1(){
String sqlCmd="INSERT INTO TEST_TABLE " +
"(CD, NAME, DEPT) VALUES (?, ?, ?)";
jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sqlCmd, new Object[] {"INSERT1",
"INSERT1","INSERT1"
});
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
下面是我的Dao2Impl类代码:
@Repository
public class Dao2Impl implements Dao2 {
@Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void insert2(){
String sqlCmd="INSERT INTO TEST_TABLE " +
"(CD, NAME, DEPT1) VALUES (?, ?, ?)";
jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sqlCmd, new Object[] {"INSERT2",
"INSERT2","INSERT2"
});
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
在spring-config.xml中,您需要设置事务支持,如下所示: -
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">