【发布时间】:2014-12-16 06:27:30
【问题描述】:
我正在构建一个 REST 服务,其中包含如下代码:
@PUT
@Produces(MediaType.APPLICATION_XML)
public Response updateOrder(
@HeaderParam("user") String user
){
CoffeeOrderDAO coffeeDAO = new CoffeeOrderDAOImpl();
....
coffeeDAO.method1();
....
coffeeDAO.method2();
....
CoffeeOrderDAOImpl
public class CoffeeOrderDAOImpl implements CoffeeOrderDAO{
Context ctx;
DataSource ds;
Connection conn;
public CoffeeOrderDAOImpl(){
try {
ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/coffeeDB");
conn = ds.getConnection();
} catch(SQLException e){
System.out.println("Exception:" + e);
} catch (NamingException ne) {
}
}
public String method1() {
}
public String method2() {
}
我的问题是我应该在调用这两个方法之前关闭method1() 和method2() 中的连接并创建一个新的CoffeeOrderDAO 对象吗?
或
对这两种方法使用相同的CoffeeOrderDAO 对象,并且只关闭method2() 中的连接
第二个选项似乎很奇怪,因为要知道何时关闭连接变得更加复杂。
那么创建多个CoffeeOrderDAO 对象是否合适,还是我遗漏了什么?
感谢您的帮助!
【问题讨论】:
-
如何将连接移出 DAO,为连接建立一个工厂
-
使用连接池代替直接连接。
-
Google for
java entitymanagerhelper -
连接可能已被 DBMS 关闭,因此最好有一个字段,在对象初始化时打开它,并假设它已准备好使用