前言
Mybatis传多个参数的一些常用方法。
@Param注解
Mapper.java接口:
int get***ByContentIdAndClassId(@Param("contentId")String contentId, @Param("classId")String classId);
Mapper.xml文件:
<select id="get***ByContentIdAndClassId" resultType="int">
SELECT
count(flag)
FROM
t_* n
WHERE
n.content_id = #{contentId,jdbcType=VARCHAR}
AND n.class_id = #{classId,jdbcType=VARCHAR}
</select>
2、索引【从0开始】
Mapper.java接口:
int get***ByContentIdAndClassId(String contentId, String classId);
Mapper.xml文件:
<select id="get***ByContentIdAndClassId" resultType="int">
SELECT
count(flag)
FROM
t_* n
WHERE
n.content_id = #{0}
AND n.class_id = #{1}
</select>
3、List【封装in】
Mapper.java接口:
List<userBean> getUserBeanList(List<String> list);
Mapper.xml文件:
<select id="getUserBeanList" resultType="userBean">
select * from t_user where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
4、参数是包装类,返回List
Mapper.java接口【使用@Param注解后xml文件不需使用parameterType标记】:
List<CslExercise> selectByExerciseQueryVo(@Param("vo")ExerciseQueryVo exerciseQueryVo);
三级标题1
Mapper.xml文件【使用别名进行映射】:
<select id="selectByExerciseQueryVo" resultType="...server.model.CslExercise">
select
exercise_id exerciseId,
exercise_name exerciseName,
exercise_type exerciseType,
task_type taskType,
pager_count pagerCount,
period_id periodId,
grade_id gradeId,
course_id courseId,
term_id termId,
sort,
create_time createTime,
end_time endTime,
state,
update_time updateTime
from
csl_exercise e
<trim prefix="WHERE" prefixOverrides="AND | OR">
<if test="vo.exerciseName!=null and vo.exerciseName!='' ">
and e.exercise_name like concat('%',#{vo.exerciseName},'%')
</if>
<if test="vo.periodId!=null and vo.periodId!='' ">
and e.period_id = #{vo.periodId}
</if>
<if test="vo.gradeId!=null and vo.gradeId!='' ">
and e.grade_id = #{vo.gradeId}
</if>
<if test="vo.courseId!=null and vo.courseId!='' ">
and e.course_id = #{vo.courseId}
</if>
<if test="vo.termId!=null and vo.termId!='' ">
and e.term_id = #{vo.termId}
</if>
<if test="vo.createTime!=null and vo.createTime!='' ">
and e.create_time >= #{vo.createTime}
</if>
<if test="vo.endTime!=null and vo.endTime!='' ">
and e.end_time <= #{vo.endTime}
</if>
</trim>
</select>
注意:
① 在对标题进行模糊搜索时,需要用concat关键字连接%。在进行时间戳比较时,大于号需要用 > 表示,小于号用 < 表示。
② trim的作用:
| 作为一个格式化标记,在此处完成where标记的功能,也可以完成set标记的功能。
| prefixOverrides去掉拼接SQL中的第一个and或or关键字。
③ 对发布时间进行降序排列:
List<CslExercise> list = cslExerciseService.selectByExerciseQueryVo(exerciseQueryVo);
Collections.sort(list,new Comparator<CslExercise>(){
@Override
public int compare(CslExercise o1, CslExercise o2) {
return o2.getCreateTime().compareTo(o1.getCreateTime());
}
});
感谢您的阅读~~