org.iworkz.habitat.dao.ContextAccess Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of habitat Show documentation
Show all versions of habitat Show documentation
A lightweight Java library for simple database access.
package org.iworkz.habitat.dao;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.sql.DataSource;
@Singleton
public class ContextAccess {
private final ThreadLocal context = new ThreadLocal() {
@Override
protected Context initialValue() {
return createContext();
}
};
@Inject
protected DataSourceProvider dataSourceProvider;
public Context getContext() {
return context.get();
}
public void startContext() {
getContext().start();
}
/**
* Start the context with a custom dataSource
* @param dataSource
*/
public void startContext(DataSource dataSource) {
Context contextToStart = getContext();
contextToStart.setDataSource(dataSource);
contextToStart.start();
}
public void closeContext() {
try {
getContext().close();
} finally {
context.remove();
}
}
protected Context createContext() {
return new Context(dataSourceProvider.getDataSource());
}
// /**
// * Intended to be used in standalone mode when the dataSourceProvider is
// * not injected.
// *
// * @param dataSource
// */
// protected void setDataSource(final DataSource dataSource) {
// this.dataSourceProvider = new AbstractDataSourceProvider(null) {
// @Override
// protected DataSource createDataSource(Object options) {
// return dataSource;
// }
// };
// }
//
protected DataSource getDataSource() {
return dataSourceProvider.getDataSource();
}
}