zoukankan      html  css  js  c++  java
  • 实体对象转QueryWrapper 便捷实现条件查询

    mybatis plus中提供了QueryWrapper做条件查询,

    方法定义是public Children eq(boolean condition,R column,java.lang.Object val)

    参数:condition - 执行条件;column - 字段;val - 值

    我们通常是这样写的,

     1    public IhTimeSchedule  getTimeSchedule(String serviceCode,String appointDate, String noonType,
     2                                            String appointTimeInterval, String deptCode, String doctorCode,
     3                                            String clinicTypeCode,String serviceType) {
     4         QueryWrapper<IhTimeSchedule> wrapper=new QueryWrapper<IhTimeSchedule>()
     5                 .eq("DEPT_CODE",deptCode)
     6                 .eq("SERVICE_CODE",serviceCode)
     7                 .eq(StringUtils.isNotBlank(doctorCode),"DOCTOR_CODE",doctorCode)
     8                 .eq("CLINIC_DATE",appointDate+" 00:00:00")
     9                 .eq(StringUtils.isNotBlank(noonType),"NOON_TYPE",noonType).
    10                 eq(StringUtils.isNotBlank(appointTimeInterval),"TIME_DIVISION",appointTimeInterval).
    11                 eq("CLINIC_TYPE_CODE",clinicTypeCode);
    12         IhTimeSchedule schedule = scheduleMapper.selectOne(wrapper);
    13         return  schedule;
    14     }

    也可以这样写(省去写列名的麻烦)

     1 public List<HpSystemConfig> queryConfig(HpSystemConfig config) {
     2         if(config==null){
     3             throw new RRException(ResultCode.PARAM_IS_BLANK);
     4         }
     5         LambdaQueryWrapper<HpSystemConfig> wrapper=new LambdaQueryWrapper<>();
     6         wrapper.eq(StringUtils.isNotBlank(config.getConfigName()),HpSystemConfig::getConfigName,config.getConfigName()).
     7                 eq(StringUtils.isNotBlank(config.getConfigValue()),HpSystemConfig::getConfigValue,config.getConfigValue())
     8                 .eq(StringUtils.isNotBlank(config.getDeptCode()),HpSystemConfig::getDeptCode,config.getDeptCode())
     9                 .eq(StringUtils.isNotBlank(config.getUnitsCode()),HpSystemConfig::getUnitsCode,config.getUnitsCode())
    10                 .eq(config.getId()!=null,HpSystemConfig::getId,config.getId());
    11         return this.baseMapper.selectList(wrapper);
    12     }
     1 @Data
     2 @TableName("HP_SCHEDULING_RECORD")
     3 @ApiModel
     4 public class HpSchedulingRecord implements Serializable {
     5 
     6     private static final long serialVersionUID = 1L;
     7 
     8     @TableId(value = "ID", type = IdType.ID_WORKER)
     9     private Long id;
    10 
    11     @ApiModelProperty(value = "医院编号")
    12     @TableField("HSR_HOSPOTALCODE")
    13     private String hsrHospotalcode;
    14 
    15     @ApiModelProperty(value = "医生编号")
    16     @TableField("HSR_DOCTOR")
    17     private Integer hsrDoctor;
    18 
    19     @ApiModelProperty(value = "房间编号")
    20     @TableField("HSR_ROOM")
    21     private Integer hsrRoom;
    22 
    23     @ApiModelProperty(value = "科室编号")
    24     @TableField("HSR_DEPT")
    25     private Integer hsrDept;
    26 
    27     @ApiModelProperty(value = "排班日期 形如yyyy-MM-dd")
    28     @TableField("HS_SHIFT_DATE")
    29     private String hsShiftDate;
    30 
    31 
    32 }

    不难看出,当实体类中很多属性都需要作为查询条件的时候,QueryWrapper就需要定义的很长,也比较麻烦。

    可以看到上面我们的实体类,每个属性都用mybatis注解标明了数据库表的列名,所以我就想,不如利用反射,写一个工具类,根据实体类自动生成QueryWrapper。

    思路:

    1.传入实体类对象作为参数,获取这个对象的Class对象。

    2.遍历实体类声明的每个属性

    3.获取属性上的mybatis注解TableField或者TableId,注解的value值即是数据库表的列名

    4.构造QueryWrapper的eq条件(get方法返回值类型不同,则执行条件的判断有不同)

    具体实现如下

     1 public static QueryWrapper entity2Wrapper(Object obj) {
     2         Class<?> aClass = obj.getClass();
     3         Field[] fields = obj.getClass().getDeclaredFields();
     4         QueryWrapper wrapper = new QueryWrapper();
     5         //遍历属性
     6         for (Field field : fields) {
     7             Method method = null;
     8             try {
     9                 String fieldName = field.getName();
    10                 //跳过serialVersionUID
    11                 if (fieldName.equals("serialVersionUID")) {
    12                     continue;
    13                 }
    14                 //获取属性上的注解
    15                 TableField fieldAnnotation = field.getAnnotation(TableField.class);
    16                 TableId idAnnotation = field.getAnnotation(TableId.class);
    17                 //拿到列名
    18                 String value = fieldAnnotation == null ? idAnnotation.value() : fieldAnnotation.value();
    19                 //get方法
    20                 method = aClass.getDeclaredMethod("get" + captureName(fieldName), null);
    21                 Object returnValue = method.invoke(obj);
    22                 if (returnValue instanceof String) {
    23                     String str = (String) returnValue;
    24                     wrapper.eq(StringUtils.isNotBlank(str), value, returnValue);
    25                 } else {
    26                     wrapper.eq(returnValue != null, value, returnValue);
    27                 }
    28 
    29             } catch (Exception e) {
    30                 e.printStackTrace();
    31                 return null;
    32             }
    33         }
    34         return wrapper;
    35     }
     1   /**
     2      * 将字符串的首字母转大写
     3      *
     4      * @param str 需要转换的字符串
     5      * @return
     6      */
     7     private static String captureName(String str) {
     8         // 进行字母的ascii编码前移,效率要高于截取字符串进行转换的操作
     9         char[] cs = str.toCharArray();
    10         cs[0] -= 32;
    11         return String.valueOf(cs);
    12     }

    使用方式如下

    public List<HpQueueCallRoom> queryRoom(HpQueueCallRoom room) {
       if(room==null){
    throw new RRException(ResultCode.PARAM_IS_BLANK);
    }
    QueryWrapper queryWrapper = WrapperUtil.entity2Wrapper(room);
    return this.baseMapper.selectList(queryWrapper);
    }
    
    

    是不是简单了很多,通过工具类得到了QueryWrapper对象后,还可以链式附加别的需要的条件,比如select,orderBy.

    swagger2测试

    如下图,符合预期。

     

  • 相关阅读:
    2-4 递增链表的插入 链表
    KMPnext数组自看
    Shortest Prefixes POJ
    Xor Sum HDU
    Immediate Decodability HDU
    Repository HDU
    "strcmp()" Anyone? UVA
    Remember the Word UVALive
    A Magic Lamp HDU
    Check Corners HDU
  • 原文地址:https://www.cnblogs.com/wsw-tcsygrwfqd/p/15189866.html
Copyright © 2011-2022 走看看