java 在 EJB 中注入数据源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13550427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Injecting datasource in EJB
提问by LuckyLuke
When you inject a datasource in your application and get a connection by invoking getConnection()
on it, are you supposed to close the connection?
当您在应用程序中注入数据源并通过调用获得连接getConnection()
时,是否应该关闭连接?
回答by Arjan Tijms
Even though the datasource itself is container managed, the API indeed requires the programmer to close connections. This is different from a couple of other container managed resources (like the entity manager), where the container takes care of closing. Note that closing here in the majority of cases doesn't actuallycloses the connection here, but returns the connection to a connection pool.
尽管数据源本身是容器管理的,但 API 确实需要程序员关闭连接。这与其他几个容器管理的资源(如实体管理器)不同,后者由容器负责关闭。请注意,在大多数情况下,此处关闭实际上并未关闭此处的连接,而是将连接返回到连接池。
As a rule of thumb, if you use a factory-ish resources to obtain one or more other resources from that can be closed, you have to close them. Otherwise the container does this.
根据经验,如果您使用工厂式资源获取一个或多个其他可以关闭的资源,则必须关闭它们。否则容器会这样做。
Since Connectionimplements AutoCloseable, you can use a try-with-resources block for this:
由于Connection实现了AutoCloseable,您可以为此使用 try-with-resources 块:
@Stateless
public class MyBean {
@Resource(lookup = "java:/app/datasource")
private DataSource dataSource;
public void doStuff() {
try (Connection connection = dataSource.getConnection()) {
// Work with connection here
} catch (SQLException e) {
throw new SomeRuntimeException(e);
}
}
}
回答by Miljen Mikic
Of course, otherwise you'll exhaust your connection pool. It's best to do this in finally block:
当然,否则你会耗尽你的连接池。最好在 finally 块中执行此操作:
@Resource(mappedName="jndi/yourDatasource")
DataSource ds;
..
Connection conn = null;
try {
conn = ds.getConnection();
//PERFORM QUERY, ETC..
}
catch(SQLException ex) {
//EXCEPTION HANDLING
}
finally {
try {
if(conn != null)
conn.close();
}
catch(SQLException ex) {..}
}