gpt4 book ai didi

java - Spring mvc : Transactional annotation

转载 作者:行者123 更新时间:2023-12-04 05:18:52 25 4
gpt4 key购买 nike

我有两张 table EmployeeAddress如图:

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同时插入 employeeaddress表属性。我在这里有点困惑。是否 @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 ?

最佳答案

尽管@Transactional 注释可以完成这项工作,但事务通常是在服务级别上定义的。这样,一个业务调用就在一个事务中,确保一切成功或失败。

你可以结合 jdbctemplate 阅读@transactional here

关于java - Spring mvc : Transactional annotation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13912232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com