I am having a requirement where i need to insert some employee data into db2 database and below is the code for that :
@Log4j2
@Service
@Transactional
public class EmployeeServiceImpl extends EmployeeService{
@Autowired
private EmployeeDataRepository employeeDataRepository;
@Override
@Transactional(rollbackOn = {DataAccessException.class})
public void insertEmployeeData(List<Employee> employeeList){
try{
employeeDataRepository.insertEmployeeData(employeeList);
}catch(DataAccessException ex){
log.error("Exception whie inserting data in db {}",ex.getMessage());
}
}
@Log4j2
@Repository
public class EmployeeDataRepositoryImpl implements EmployeeDataRepository{
@Autowired
private DataSource dataSource;
@Value("${db.schema}")
private String schema;
@Override
public void insertEmployeeData(List<Employee> employeeList){
this.jdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("Employee");
for(Employee emp : employeeList){
Map<String,Object> parameters = new HashMap<String,Object>();
parameters.put("name", emp.name);
parameters.put("age", emp.age);
parameters.put("dateOfJoining", emp.dateOfJoining);
parameters.put("address", emp.address);
parameters.put("salary", emp.salary);
jdbcInsert.execute(parameters);
log.info("Created Record Name = " + name + " Age = " + age + " dateOfJoining = "+dateOfJoining);
}
return;
}
}
using spring datasource properties datasource is configured and injected into EmployeeDataRepositoryImpl
class. I am using SimpleJdbcInsert
to insert data into db2 table. For transnational handling i am using
@Transactional(rollbackOn = {DataAccessException.class})
on method. When the data is inserted one by one then if something goes wrong at db level then it should rollback but eventually its not happening. Also i tried putting annotation at class level but there is no luck. Please let me know if i am missing anything ?
You are having a couple of things mixed up here.
Your code should read like this, this is enough.
@Transactional
public void insertEmployeeData(List<Employee> employeeList){
employeeDataRepository.insertEmployeeData(employeeList);
}