Hi, How can i do operation of others dao with one transaction?

I have dao which methods should be within one transaction What is the best way to do it correctly? Car dao has following method

public Car findCar(int numOfPas,String carCategory){
        String query = "SELECT*FROM car_info WHERE numOfPas = ? AND carCategory=? AND carState='ready' ORDER BY RAND() LIMIT 1;";
        Car foundCar = null;
        ResultSet resultSet = null;
        try (Connection connection = MySQLDAOFactory.getConnection();
             PreparedStatement statement = connection.prepareStatement(query)){
            statement.setInt(1,numOfPas);
            statement.setString(2,carCategory);
            resultSet =statement.executeQuery();
            if(resultSet.next()){
                foundCar = new Car();
                foundCar.setCarId(resultSet.getInt("carId"));
                foundCar.setCarCategory(resultSet.getString("carCategory"));
                foundCar.setNumOfPas(resultSet.getInt("numOfPas"));
                foundCar.setCarState(resultSet.getString("carState"));
                foundCar.setCarName(resultSet.getString("carName"));
                foundCar.setCarImage(manager.byteToImage(resultSet.getBytes("carImage")));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return foundCar;

    }

And Order Dao has following

@Override
    public boolean insertOrder(Order order) {
        int rowNum = 0;
        String query = "INSERT INTO user_order(userId,carId,userAddress,userDestination,orderCost,orderDate) values(?,?,?,?,?,?)";
        ResultSet keys = null;
        try (Connection connection = MySQLDAOFactory.getConnection();
             PreparedStatement statement = connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS)){

            statement.setInt(1,order.getUserId());
            statement.setInt(2,order.getCarId());
            statement.setString(3, order.getUserAddress());
            statement.setString(4, order.getUserDestination());
            statement.setDouble(5,order.getOrderCost());
            statement.setTimestamp(6, Timestamp.valueOf(order.getOrderDate()));
            rowNum = statement.executeUpdate();
            keys = statement.getGeneratedKeys();
            if(keys.next()){
                order.setOrderId(keys.getInt(1));
            }

        } catch (SQLException throwables) {

            throwables.printStackTrace();
        }

        return rowNum>0;
    }

How can I put these action in one transaction? I receive connection by Apache dhcp connection pool.

Edited

This is class where I get connection public class MySQLDAOFactory extends DAOFactory {

    public static Connection getConnection(){

        Connection conn = null;
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/UsersDB");
            conn = ds.getConnection();
        } catch (NamingException | SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }
    @Override
    public CarDao getCarDao() {
        return new MySQLCarDao();
    }

    @Override
    public UserDao getUserDao() {
        return new MySQLUserDao();
    }
    @Override
    public OrderDao getOrderDao() {
        return new MySQLOrderDao();
    }

    @Override
    public CarCategoryDao getCarCategoryDao() {
        return new MySQLCarCategoryDao();
    }
}

Answer

There are a lot of different ways to manage transactions. Given your code, the simplest way would be to:

in a try block:

  1. Create your connection in the caller that wraps both calls
  2. Execute connection.setAutoCommit(false)
  3. Call each of the methods findCar() and insertOrder()
  4. Call connection.commit();

in the catch block:

call connection.rollback()

The connection is not created outside those functions, so don’t forget to remove the connection setup from each function.