开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情
MyBatis 是一款优秀的持久层框架;它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和Java POJO为数据库中的记录。
1、带条件的分页查询
/**
* @param pageBean
* @param subarea
* @throws Exception
*/
@Override
public void selectByConditions(PageBean pageBean, Subarea subarea) throws Exception {
PageHelper.startPage(pageBean.getCurrentPage(),pageBean.getPageSize());
List<Subarea> subareas = subareaMapper.selectByConditions(subarea);
PageInfo<Subarea> subareaPageInfo = new PageInfo<>(subareas);
pageBean.setTotal(subareaPageInfo.getTotal());
pageBean.setRows(subareaPageInfo.getList());
}
2、批量处理及批量模糊处理
id in
<foreach item="Id" collection="list" open="(" separator="," close=")">
#{Id}
</foreach>
<if test="Id != null and Id != '' ">
AND
<foreach item="IdStr" collection="Id.split(',')" open="(" separator="OR" close=")">
id LIKE CONCAT('%', #{IdStr}, '%')
</foreach>
</if>
3、mybatis动态查询
<!-- choose(判断参数) - 按顺序将实体类 User 第一个不为空的属性作为:where条件 -->
<select id="selectControlTableColumnByTableColumnIdAndIsUpdateOrIsDelete" parameterType="com.uama.mdm.model.mdata.MdControlTableColumn" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_list"></include>
FROM md_control_table_column u
<where>
<choose>
<when test="isUpdate !=null ">
AND u.is_update = #{isUpdate, jdbcType=INTEGER}
</when>
<when test="isDelete != null">
AND u.is_delete = #{isDelete, jdbcType=INTEGER}
</when>
<otherwise>
</otherwise>
</choose>
<if test="tableColumnId != null">
AND table_column_id = #{tableColumnId}
</if>
</where>
</select>
4、mybatis动态set
<update id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity">
UPDATE STUDENT_TBL
<set>
<if test="studentName != null and studentName != '' ">
STUDENT_TBL.STUDENT_NAME = #{studentName},
if>
<if test="studentSex != null and studentSex != '' ">
STUDENT_TBL.STUDENT_SEX = #{studentSex},
if>
<if test="studentBirthday != null ">
STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
if>
<if test="studentPhoto != null ">
STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},
if>
<if test="classId != '' ">
STUDENT_TBL.CLASS_ID = #{classId}
if>
<if test="placeId != '' ">
STUDENT_TBL.PLACE_ID = #{placeId}
if>
set>
WHERE STUDENT_TBL.STUDENT_ID = #{studentId};
</update>
5、${}和#{}的区别
-
#{}将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #{user_id}如果传的值是12将被解析为order by "12";
-
{user_id}如果传的值是12将被解析为order by 12;如果传的值是id,将被解析为order by id;
-
${}有sql注入风险。
-
${}方式一般用于传入数据库对象,例如传入表名,字段名。
-
#{}的参数替换是发生在 DBMS(数据库管理系统) 中,而 ${} 则发生在动态解析过程中。
即:select * from user where name = #{name}; #{}在预编译时参数部分用一个占位符 ? 代替, 例子:select * from user where name = ? ${}在动态解析时直接简单替换参数,例子:select * from user where name = xxx MyBatis排序时使用order by 动态参数时需要注意,用${}而不是#{}