欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis自带的selectByExample修改查询条件

程序员文章站 2024-03-02 08:05:58
...

在使用selectByExample时,可以设置查询条件的
1、相等
2、模糊查询
3、时间在某个时间段内
下面举例说明如何使用:

public List<SysHospitalizationDTO> getPageList(SysHospitalizationQuery sysHospitalizationQuery, String sort, String sortOrder) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(getDateFormat());
        Date todayDate = getTodayDate();
        List<SysHospitalization> list = sysHospitalizationDao.selectByExample(getExample(sysHospitalizationQuery)).stream().collect(Collectors.toList());
        }


private Example getExample(SysHospitalizationQuery sysHospitalizationQuery) {
        Example example = new Example(SysHospitalization.class);
        Example.Criteria criteria = example.createCriteria();

        //模糊查询
        if (sysHospitalizationQuery.getpName() != "") {
            criteria.andLike("pName", "%" + sysHospitalizationQuery.getpName() + "%");
        }
        //相等查询
        if (sysHospitalizationQuery.gethId() != "") {
            criteria.andEqualTo("hId", sysHospitalizationQuery.gethId());
        }
        if (sysHospitalizationQuery.gethArea() != 0) {
            criteria.andEqualTo("hArea", sysHospitalizationQuery.gethArea());
            ;
        }
        //筛选时间--在某个时间段内
        if (sysHospitalizationQuery.gethDate() != "") {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Date dateBegin = null;
            Date dateEnd=null;
            try {
                dateBegin = sdf.parse(sysHospitalizationQuery.gethDate());
                dateEnd = sdf.parse(sysHospitalizationQuery.gethDate());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            Calendar cal = Calendar.getInstance();
            cal.setTime(dateEnd);
            cal.add(Calendar.DATE, 1);
            criteria.andBetween("hDate",dateBegin,new Date());
        }
        return example;
    }