
org.iworkz.habitat.dao.Context Maven / Gradle / Ivy
package org.iworkz.habitat.dao;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public class Context {
private boolean started;
private Connection connection;
private DataSource dataSource;
public Context(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getConnection() {
checkState();
if (connection == null) {
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("Can not get connection",e);
}
}
return connection;
}
protected void checkState() {
if (!started) {
throw new IllegalStateException("The context has not been started.");
}
}
public void start() {
if (started) {
throw new IllegalStateException("The context is already started.");
}
started = true;
}
public void close() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection = null;
}
}
started = false;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy