Reputation: 4002
I have two tables Employee
and Address
as shown:
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
}
Now i want to implement Transactional
while inserting the employee
and address
table attributes. I am abit confused here. Does @transactional
annotation over the method does the required job? So far i understood that. Also, is it best practice to insert address from where i am inserting employee
attributes? I also read somewhere that the transactional should be implemented from service layer than Dao. How would transactional can be implemented in this case?
EDIT
Since it is recommended to use @transactional
in service layer, service layer became like:
@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);
}
}
is it the right way to perform transactional? Also can anyone explain @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
instead of plain @Transactional ?
Upvotes: 2
Views: 3434
Reputation: 1331
Alltough the @Transactional annotation would do the job, transactions are usually defined on service level. This way one business call is in one transaction, making sure everything succeeds or fails together.
you can read about @transactional in combination with jdbctemplate here
Upvotes: 3