【发布时间】:2017-10-05 20:15:39
【问题描述】:
我有一个使用 JSP 模型 2 架构的网络应用程序。
我也使用 DAO 模式;特别是,不同的方法需要像 productID 这样的值,我希望它是唯一的。
/**
* Updates the productID that is unique per JVM run.
* @return the updated value of <i>productID</i>
* @throws ClassNotFoundException if an error occurs with the connection to the database
*/
public static synchronized int createProductID() throws ClassNotFoundException{
int maxID = QueriesDAO.maxIDInDatabase("product");
while(productID <= maxID) {
productID++;
}
return productID++;
}
该方法查询数据库并返回一个新 ID,该 ID 存储在 private static int productID = 0; 中(0 是分配的第一个值)。
我想问的是:我应该把那个查询和那个变量放在哪里?
目前,我有一个名为 DAO 的包,其中包含所有查询,例如查询 UserDAO.java 上的用户或查询 ProductDAO.java 上的产品等等。 createProductID() 方法和链接的变量存储在 Main 类中,但在我看来这不是正确的位置。我怎样才能改变我的模式?
使用接口可以解决问题吗?但是有了这个接口,我就不能拥有可以托管productID 变量的私有字段..
【问题讨论】:
-
答案是“不要那样做”。例如,如果您在多台服务器上运行副本怎么办?相反,请使用数据库序列或让您的持久性提供程序为您执行此操作。
标签: java design-patterns dao