B
B
Biaci_Anj2022-03-26 23:48:16
Java
Biaci_Anj, 2022-03-26 23:48:16

What is the correct way to work with transactions in Service layer using JDBC (without Hibernate and Spring)?

I have a method that accesses two DAOs

void setStatusDeclinedAndRefund() {
// sets Order status to DECLINED
// refund money to user's balance
}


I placed it at the service level, but how can I now execute it in a transaction?

Is it really the only way out is to pass the Connection as an argument to all DAO methods in order to get the connection from the pool in the service and give the DAO?

PS

This is the class from which I take Connection ( a lot of code, the main thing I wanted to show is that I use ComboPooledDataSource ).

public class DBManager {
  private static DBManager instance;
  private ComboPooledDataSource cpds;

  /**
   * Singleton.
   */
  public static synchronized DBManager getInstance() {
    if (instance == null) {
      instance = new DBManager();
    }
    return instance;
  }

  private DBManager() {
    try {
      init();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Create pool.
   *
   * @throws Exception the exception
   */
  private void init() throws Exception {
    createPool();
  }

  /**
   * Establishes a connection to the database.
   *
   * @return the connection to the database
   */
  public Connection getConnection() {
    Connection conn = null;
    try {
      conn = this.cpds.getConnection();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return conn;
  }

  /**
   * Closes the connection.
   *
   * @param conn closes the database connection
   */
  public void closeConnection(Connection conn) {
    try {
      conn.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  /**
   * Gets utils properties.
   *
   * @return the databases properties
   * @throws IOException by failed or interrupted I/O operations.
   */
  private Properties getProperties() throws IOException {
    Properties props = new Properties();
    props.load(DBManager.class.getResourceAsStream("/db.properties"));
    return props;
  }

  /**
   * Create a pool.
   *
   * @throws Exception the exception
   */
  private void createPool() throws Exception {
    Class.forName("org.postgresql.Driver");
    Properties props = getProperties();
    cpds = new ComboPooledDataSource();
    cpds.setDriverClass(props.getProperty("driver"));
    cpds.setJdbcUrl(props.getProperty("url"));
    cpds.setUser(props.getProperty("user"));
    cpds.setPassword(props.getProperty("password"));
    cpds.setMaxStatements(180);
  }

}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question