How to make service level transactions

My project has a DAO layer. Here is my UsersDao interface and its implementation 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;
        }
    }

Here are my service level classes and interfaces .

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);

}

What do I need to write to my service method so that I can roll back when an exception is thrown? How to write a transaction correctly in my service method? Could you show me some examples? Thanx!

+4
source share
1 answer

Firstly, if an exception occurs, your dataset will not be inserted and therefore there will be a rollback.

, , . , . , , , X, , . . - , . .

JDBC- , https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html

0

Source: https://habr.com/ru/post/1650243/


All Articles