我有以下場景,我有2個服務層負責將數據插入emp表和dept表。Spring傳播requires_new不起作用
我已經寫了查詢失敗插入的部門表,即deptno無法接受長度> 2的deptno,因此它不會插入數據庫由於DataIntegrity違反。我不希望我以前的交易依賴於此交易。因此使用了REQUIRES_NEW傳播級別。
這是我的代碼。
@Component
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DeptService deptService;
@Transactional(propagation = Propagation.REQUIRED)
public boolean createEmployee() {
employeeDao.insertEmployee();
deptService.createDept();
return false;
}
}
@Component
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptDao deptDao;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public boolean createDept() {
deptDao.insertDepartment();
return false;
}
}
下面是DAO層
@Component
public class EmployeeDaoImpl implements EmployeeDao {
private String empInsert = "INSERT INTO emp VALUES ('1000','Ravi','CLERK','7782','1990-01-01','1235.00',NULL,'50');";
@Autowired
private JdbcTemplate jdbcTemplate;
public boolean insertEmployee() {
int n = jdbcTemplate.update(empInsert);
return true;
}
}
@Component
public class DeptDaoImpl implements DeptDao {
private String deptInsert = "INSERT INTO dept VALUES ('500','MATERIAL','ALASKA');";
@Autowired
private JdbcTemplate jdbcTemplate;
public boolean insertDepartment(){
jdbcTemplate.update(deptInsert);
return true;
}
}
下面的代碼是從主類稱爲
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("txrequirednew.xml");
EmployeeService es = (EmployeeService) context.getBean("employeeServiceImpl");
es.createEmployee();
}
下面是我的應用程序上下文:
<beans>
<context:annotation-config/>
<context:component-scan base-package="txrequirednew">
</context:component-scan>
<bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/tejadb"></property>
<property name="username" value="root"/>
<property name="password" value="sai"/>
</bean>
<!-- Dao Configurations-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
當我嘗試執行,這兩個transa ctions正在回滾。但我不想讓我的第一筆交易回滾。
這是什麼我在這裏失蹤,這導致兩個交易回滾? 我該如何解決這個問題。
謝謝A.R Afsharian。它爲我工作。 – user3777919