Java – how to conduct transactions in the service layer
There is a Dao layer in my project This is my usersdao interface, which implements usersdaoimpl
public interface UsersDao { public Users insert(Users object); } public class UsersDaoImpl implements UsersDao { @Override public Users insert(Users object) { String sqlQuery = null; PreparedStatement stmt = null; try (Connection connection = DbConnector.getConnection()) { sqlQuery = "INSERT INTO `users`(login,password,passwordSalt,name,surname)" + " values (?,?,?);"; stmt = connection.prepareStatement(sqlQuery); stmt.setString(1,"fsf"); stmt.setString(2,"f"); stmt.setString(3,"af"); stmt.setString(4,"fddsg"); stmt.setString(5,"sdgsgd"); stmt.executeUpdate(); stmt.close(); return object; } catch (sqlException e) { System.err.println(e.getMessage()); return null; } }
This is my service layer class and interface
public interface UseRSService{ public Users insert(Users object); } public class UseRSServiceImpl implements UseRSService{ UsersDaoImpl users = new UsersDaoImpl(); public Users insert(Users object){ return users.insert(object); }
I need to write my service method. Can I roll back when exception is caught? How do I record write transactions in my service methods? Can you tell me some examples? Thank you list!
Solution
First, if an exception occurs, the dataset is not inserted, so it is rolled back
Transactions are used if you have separate atomic operations linked This means that if you need to roll back an error If you want to implement it manually now, you must review what you have done to point X and undo everything that happened But it is very error - prone and very inflexible Therefore, I recommend using the underlying DB system for this purpose, which will integrate this function Or use a persistence layer
If you are using the JDBC compare driver, check here https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html