How to use jndi datasource in dao?

て烟熏妆下的殇ゞ 提交于 2019-12-13 05:12:56

问题


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 ?


回答1:


I have come across this many times before. I would have a class called CommonDao that is similar to your AbstractRepository. The Connection or DataSource was a variable that belonged to CommonDao, but it was not static... so every instance of CommonDao had their own copy. So my answer is that as long as you do not make AbstractRepository.ds static then you should be fine.

The pros for doing this (having DataSource be part of AbstractRepositor but not be static) is that you have one common way for obtaining your DataSource and can overwrite it if need be by the subclasses (this would require making ds protected).



来源:https://stackoverflow.com/questions/28001795/how-to-use-jndi-datasource-in-dao

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!