编码习惯养成记

  • 实诚地“见名知意”命名,一定要特别明显的见名知意命名。
  • 关系到数据库查询,即使是很小的数据量,也一定要做到同一个业务方法能查询一次绝对不查询两次。


natureService.get(Integer.valueOf(Cnature.getNature()))查询只进行一次!!!!


  • 对于数据库查询当需要查询的条件过多时,要简化查询语句。

case  "companyNatures":
    //客户性质ids
    String[] ids = value.toString().split(",");
    List<Integer> customeIds = new ArrayList<>();
    if(ids.length > 0){
        for (String id : ids) {
            //去中间表获取所有客户id
            CustomerNature customerNature = new CustomerNature();
            customerNature.setNature(Byte.valueOf(id));
            List<CustomerNature> obj = customerNatureService.getObj(customerNature);
            for (CustomerNature nature : obj) {
                customeIds.add(nature.getCustomerId());
            }
        }
    }
    criteria.andIn("id",customeIds);
    break;

将以上内容用 criteria.andCondition("id in (SELECT cn.`customer_id`  FROM `customer_nature` cn WHERE cn.`nature` IN ("+value.toString()+"))"); 替换

criteria.andCondition("id in (SELECT cn.`customer_id`  FROM `customer_nature` cn WHERE cn.`nature` IN ("+value.toString()+"))");
  • 保存实体类对象到数据库时,不能对使用同一个对象赋值保存。

//中间表信息更新
//客户性质ids
String[] ids = customer.getCompanyNatures().split(",");
CustomerNature customerNature = new CustomerNature();
customerNature.setCustomerId(customer.getId());
customerNatureService.deletObj(customerNature);
for (String id : ids) {
    customerNature.setNature(Byte.valueOf(id));
    customerNatureService.save(customerNature);
}

以上复用同一个对象保存数据到数据库,运行项目会报错。

//中间表信息更新
//客户性质ids
String[] ids = customer.getCompanyNatures().split(",");
CustomerNature customerNature = new CustomerNature();
customerNature.setCustomerId(customer.getId());
customerNatureService.deletObj(customerNature);
for (String id : ids) {
    customerNature.setNature(Byte.valueOf(id));
    customerNatureService.save(customerNature);
    customerNature.setId(null);
}


猜你喜欢

转载自blog.csdn.net/qq_34638435/article/details/80682977