这是最好的编码实践,分配给变量或从数据库中获取

时间:2017-11-24 10:50:18

标签: java hibernate spring-mvc

在我的编码片段中

customer.java

  public class customer{

   private Double avgSalePrice;
   private Double costOfScrap;
   private Double minCastingWt;


    //getters and setters
 }

商业逻辑

第一种方式:

public HashMap<String, Object> prepareCustomer() {

  Integer customerPkey=1;
  HashMap<String, Object> responseMap = new HashMap<String, Object>();

  //get the customer object from the data base and assigning scrapCost to responseMap from getterProperty
  responseMap.put("scrapCost",customerService.readCustomerInfo(customerPkey).getCostOfScrap());

  //get the customer object from the data base  and assigning scrapCost to responseMap from getterProperty
  responseMap.put("salePrice",customerService.readCustomerInfo(customerPkey).getAvgSalePrice());

  //get the customer object from the data base  and assigning minCastingWt to responseMap  from getterProperty
  responseMap.put("minCastingWt",customerService.readCustomerInfo(customerPkey).getMinCastingWt());

    return responseMap;
}

第二种方式:

public HashMap<String, Object> prepareCustomer() {

  Integer customerPkey=1;

  HashMap<String, Object> responseMap = new HashMap<String, Object>();

  Customer customer = customerService.readCustomerInfo(customerPkey);

  responseMap.put("scrapCost",customer.getScrapCost());
  responseMap.put("salePrice",customer.getSalePrice());
  responseMap.put("minCastingWt",customer.getMinCastingWt());

  return responseMap;
}

现在我的怀疑是

1.从数据库中获取客户行并将所有三次分配给HashMap是最佳实践(以第一种方式显示)

(OR)

2.从数据库中获取客户行以进行单次提取然后分配给客户对象并使用对象的引用将所有三个值放在responseMap中是最佳实践(以第二种方式显示)

我需要清楚解释两种方式的时序和内存分配

提前致谢...:)

1 个答案:

答案 0 :(得分:0)

最好的方法是:

public HashMap<String, Object> prepareCustomer(Customer customer) {
  HashMap<String, Object> responseMap = new HashMap<String, Object>();

  responseMap.put("scrapCost", customer.getScrapCost());
  responseMap.put("salePrice", customer.getSalePrice());
  responseMap.put("minCastingWt", customer.getMinCastingWt());

  return responseMap;
}
  

从数据库中获取客户行并分配给所有三次的HashMap

不会从数据库中提取

Customer三次。它将仅被提取一次,对于客户的所有后续请求,将从Session返回相同的客户。 Session被称为第一级缓存。

即使您为同一个客户拨打三个电话,如果您呼叫客户一次,也会花费相同的时间和内存。

您可以使用guava中的ImmutableMap构建Map

ImmutableMap.of("scrapCost", customer.getScrapCost(),
                "salePrice", customer.getSalePrice(),
                "minCastingWt", customer.getMinCastingWt());