I have this method that is supposed to be executed in a transaction. As I get and close connections in DAO, I suppose that it should to be a part of DAO.
void setStatusDeclinedAndRefund() {
// sets Order status to DECLINED
// refund money to user's balance
}
But I though DAO implementations should implement only CRUD methods, is it ok for such a method to be there?
If it violates, I can call 2 update methods from Service layer ( but how am I supposed to create a transaction there? Open connection -> pass it DAO - seems like a pretty bad idea )
UPD: The class I get connections from ( just to show that I use ComboPooledDataSource for connections ).
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);
}
}