![](/img/trans.png)
[英]JPA: How do I avoid loading an object simply so I can store its ID in the database?
[英]how to store data retrieved from database into a variable so that I can avoid hitting database again
我有一个webapp,需要通过JDBC从数据库检索数据并在前端显示它。 它是静态数据,不会被更改。 因此,我只需要检索一次数据并将其存储在静态变量中,这样我就可以每次使用该数据,而不必查询数据库。 下面是示例代码:
public class SampleClass(){
static Map<String, BigDecimal> productMap = null;
public Map<String, BigDecimal> getDatafromDB(Connection conn, PreparedStatement stmt, ResultSet rs) throws SQLException{
if(productMap == null){
productMap = getProductID(conn, stmt, rs);
}
return productMap;
}
public Map<String, BigDecimal> getProductID(Connection conn, PreparedStatement stmt, ResultSet rs) throws SQLException {
logger.debug("retrieving product ID's from product table..");
Map<String, BigDecimal> productMap = new HashMap<String, BigDecimal>();
stmt = conn.prepareStatement("Select * from PRODUCTTABLE");
rs = stmt.executeQuery();
logger.debug("Product ID's retrieved");
while(rs.next()){
productMap.put(rs.getString("PRODUCT_NAME"),rs.getBigDecimal("PRODUCT_ID"));
}
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
return productMap;
}
}
我正在通过http servlet请求从UI调用此方法。 我第一次运行它时,由于地图为null,因此它查询数据库并获取数据并将其发送到UI。 当我再次通过新请求再次访问servlet时,产品映射为null,并且再次查询数据库并获取数据。 由于它是一个静态变量,因此仅应在仪式上初始化一次,为什么第二个请求仍为null。 有人可以更正我的代码吗?
提前致谢
您的问题的根本原因是Servlet无内存。 因此,静态变量将无济于事。 您需要的是会话属性。
我建议将您的变量添加为会话属性。 首先,您需要创建一个实现Serializable的封装类:
public class SampleResult implements Serializable {
private Map<String, String> productMap;
public void setProductMap(Map<String, String> productMap) {
this.productMap = productMap;
}
public Map<String, String> getProductMap() {
return productMap;
}
}
现在在您的servlet中:
HttpSesssion session = request.getSession();
Map<String, String> productMap;
SampleResult result;
if (session.getAttribute("productMap") == null) {
productMap = retrievedatafromDB();
result = new SampleResult();
sampleResult.setProductMap(productMap);
session.setAttribute("productMap", result);// session attribute created
} else {
result = session.getAttribute("productMap");// retrieve session attribute
productMap = result.getProductMap();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.