我有两张桌子Employee
,Address
如图所示:
public class Employee {
private Integer id;
private String firstName;
private String lastName;
private boolean employeeStatus;
private Address address;
//getters setters
}
public class Address {
private Integer id;
private String country;
private String city;
private String street;
private Integer emp_id;
//getters setters
}
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void insertEmployee(Employee e)
{
String sql = "INSERT INTO tbl_employee (dept_id,firstName,lastName,employeeStatus) values(?,?,?,?,?)";
this.jdbcTemplate.update(sql,new
Object[]{e.getDept_id(),e.getFirstName(),e.getLastName(),e.isEmployeeStatus()});
// INSERT ADDRESS????
}
// Other Methods
}
现在我想Transactional
在插入employee
和address
表属性时实现。我在这里有点困惑。方法上的注释是否@transactional
完成了所需的工作?到目前为止,我明白了。另外,从我插入employee
属性的位置插入地址是最佳做法吗?我还在某处读到事务应该从服务层而不是 Dao 实现。在这种情况下如何实现事务性?
编辑
由于建议@transactional
在服务层中使用,服务层变成了:
@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
EmployeeDao employeeDao;
@Autowired
AddressDao addressDao;
@Override
public void insertEmployee(Employee e) {
employeeDao.insertEmployee(e);
addressDao.insertAddress(e.address);
}
}
这是执行事务的正确方法吗?也有人可以解释@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
而不是简单的 @Transactional 吗?