分享一个好的思路,既然Criteria底层实现也是用的JDBC,那么为什么不可以自己重载自动生成的方法呢?比如我现在的需求是接收前端String类型的时间字段,我数据库里存的时间类型是date,然而Criteria原生方法中没有提供String入参类型,我可以将原生方法稍作改造,以下是关于时间场景的示例说明:
这个是Criteria 中的:
public Criteria andBookingDayEqualTo(Date value) {addCriterionForJDBCDate("booking_day =", value, "bookingDay");return (Criteria) this;}
这个是我重载的:
public Criteria andBookingDayEqualToByString(String beginDate) {addCriterion("date(booking_day) =", beginDate, "bookingDay");return (Criteria) this;}
好处就是我在业务代码中不需要将前端传的时间参数格式化了,而是直接在Criteria中的用JDBC来写mysql中的date()函数来转换格式,可以理解为自己写sql语法来实现。
这是一个好思路,运用好了感觉会减少挺多代码量,举一反三可以根据自己需求,重载其他的方法,下面奉献一份我的调用实例:
public List<HosResourceVO> queryHosResource(HosResourceQuery hosResourceQuery) {HosAllocationRecordInfoPOExample hosAllocationRecordInfoPOExample = new HosAllocationRecordInfoPOExample();HosAllocationRecordInfoPOExample.Criteria criteria = hosAllocationRecordInfoPOExample.createCriteria();criteria.andAllocationDeptEqualTo(hosResourceQuery.getHospitalId());criteria.andCheckProjectEqualTo(hosResourceQuery.getCheckProject());if(StringUtils.isBlank(hosResourceQuery.getBeginDate())){Date bookingDay = new Date();//获取30天内的号源对象Date afterDay = DateUtil.addDay(new Date(), 29);criteria.andBookingDayBetween(bookingDay,afterDay);}else {criteria.andBookingDayEqualToByString(hosResourceQuery.getBeginDate());}List<HosAllocationRecordInfoPO> hosAllocationRecordInfoPOS = hosAllocationRecordInfoPOMappernfo.selectByExample(hosAllocationRecordInfoPOExample);return HosResourceConverter.convertToHosResourceVOList(hosAllocationRecordInfoPOS);}