I'm trying to do my first web project using tomcat, jsp, servlets and log4j. I have TO
like: User, Subject, Faculty etc, and DAO
objects like: UserRepository, SubjectRepository, FacultyRepository etc. With repositories I have the following hierarchy (not all entities placed):
The initialization of
DataSource
in AbstractRepository
goes this way:
public abstract class AbstractRepository<T> implements Repository<T> {
private final static Logger LOG = Logger
.getLogger(AbstractRepository.class);
private static final DataSource ds = init();
private static DataSource init() {
DataSource dataSource = null;
try {
Context initContext = new InitialContext();
dataSource = (DataSource) initContext
.lookup("java:/comp/env/jdbc/mydb");
} catch (NamingException ex) {
LOG.error("Cannot obtain a connection from the pool", ex);
}
return dataSource;
}
protected Connection getConnection() throws SQLException {
return ds.getConnection();
}
....
}
So now if repository needs a Connection
its just calls the parent getConnection()
method.
The question is it better to have one DataSource
object in AbstractRepository
and each subclass repository will get Connection
using method in parent or each subclass should have its own private final DataSource
field which would be initialized in constructor ? Then explain me: if I choose first way should I put on method getConnection synchronized
keyword ? And if I choose second way: then subclass repositories should be singletones, because every time the request comes to a servlet it creates some repository and so it will be multiple DataSources
? Or Tomcat
knows through context.xml
file how many Connections it should keep ? I've just got confused. Would you explain the best practices ? Maybe I should re-design something ?