Mybatis逆向工程example使用Order by排序
1、 需求描述
在日常对数据库操作时,需要对特定的字段进行排序,这一块的排序可以在sql语句上处理,而不用放在Java代码中,基于Mybatis的逆向工程自动生成mapper、实体类、sql语句等为我们提供了方便的使用。
2、如何使用example添加order by
2.1 首先看一下自动生成的xml中的select内容
<select id="***" parameterType="***" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> 表名 <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <!--可以看到,mybatis在这里为我们提供了order by语句,这样我们就可以在代码中直接使用--> <if test="orderByClause != null"> order by ${orderByClause} </if> </select>
2.2 如何在代码中添加order by
new一个example类,使用example类调用setOrderByClause方法,example.setOrderByClause("MONTH_ID"),这里需要注意的是,setOrderByClause方法中的参数需要用双引号引起来,参数就是需要排序的字段,名称必须和数据库中的字段名称一致。 setOrderByClause中还有其他可选参数,比如倒序等各种参数,如果需要排序多个字段,使用逗号隔开即可。
//示例 @Override public List<HsopScreenThroughFeeDetailIndicatorsDm> throughFeeDetailIndicators(String insertTime) { HsopScreenThroughFeeDetailIndicatorsDmExample example = new HsopScreenThroughFeeDetailIndicatorsDmExample(); //这个是查询语句 example.createCriteria().andInsertTimeEqualTo(insertTime); //这个是新添加的Order by语句,括号中的参数必须和数据库中的字段名一致 example.setOrderByClause("MONTH_ID"); List<HsopScreenThroughFeeDetailIndicatorsDm> list = feeDetailIndicatorsDmMapper.selectByExample(example); if (!CollectionUtils.isEmpty(list)) { return list; } return null; }