简体   繁体   中英

How to use jndi datasource in dao?

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 ?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM