简体   繁体   中英

How to make Transactions in Service Layer

I have got a DAO layer in my project. Here is my UsersDao interface and it's 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 is my Service layer 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 i need to write into my service method that i could make a rollback when exception caught? How to correclty write Transaction in my service method? Could you show me some examples? Thanx!

First of, if an exception occurs your dataset won't be inserted and therefore it is rolled back.

You use transactions if you have seperate atomic operations that are kind of chained. Which means if one errors you need to rollback. If you now want to implement it manually, you would have to look what you have done to point X and then undo all things that happened. But it's very very prone to errors and super unflexible. Therefore I recommend to use the underlying DB-System for this purpose which will have this funcionality integrated. Or use a persistence layer.

If you use JDBC compiant driver take a look here https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM