我正在学习 JDBC
连接池,使用 JNDI
获取 DataSource
实例听起来相对容易:
DataSource ds = (DataSource)ctx.lookup("jdbc/myDB");
我发现的所有教程仅在一个对象中显示此代码,但我的问题是当我有多个 DAO
对象需要从中获取数据时如何使用 DataSource
数据库。
可以在每个新的
DAO
对象的构造函数上使用上面的代码进行连接池吗?我认为相同的DataSource
每次都会返回,就像字典单例一样,持有一个 DataSource 并返回它,或者我错了,它会每次返回不同的 DataSource 吗?使用不同的池,违背了我的目的?我应该将
DataSource
保存在单例中,并且只运行JNDI
搜索一次,还是搜索开销可以忽略不计,这是一个愚蠢的优化?
最佳答案
- Is it ok to use the code above for connection pooling on every new DAO object's constructor? I think the same DataSource will be returned every time, much like a Dictionary Singleton would do, holding a single DataSource and returning it, or am I wrong and will it return a different DataSource every time and use different pools, defeating my purpose?
每次都应该返回相同的 DataSource 对象。如果它实际上不是同一个对象,那么它至少应该共享相同的底层连接池。
- Should I hold that DataSource in a Singleton and only run the JNDI search once or is the search overhead neglectable and this is a silly optimization?
与在远程数据库上执行操作相比,JNDI 的搜索开销可以忽略不计,因此无需缓存 DataSource 对象。
关于java - 如何处理连接池和DAO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44193229/