批量插入==》foreach
<insert id="insertBatch"> insert into student (name, img, sex, create_time) values <foreach collection="studentList" item="student" separator=","> ( #{student.name,jdbcType=VARCHAR}, #{student.img,jdbcType=VARCHAR}, #{student.sex,jdbcType=INTEGER}, #{student.createTime,jdbcType=TIMESTAMP} ) </foreach> </insert>
批量删除
<delete id="deleteByIds" parameterType="java.lang.Long" > delete from student where id in <foreach collection="idList" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </delete>
每一个循环的间隔加,整体开始前加”(",整体结束之后加")"
item是给循环遍历的单个个体的命名
foreach标签
- collection:表示迭代集合的名称,自定义名称,可以使用@Param注解指定
- 只有一个List/Array/Map类型参数时,如果不加@Param注解,collection分别必须填:list、array、map中的key属性
- 有多个参数时,不加@Param注解,collection和默认参数名称一致
- 如果加@Param注解,都和注解定义一致
- item:表示本次迭代获取的元素,自定义名称;表示本次迭代获取的元素,若collection为List、Set或者数组,则表示其中的元素;若collection为map,则代表key-value的value,该参数为必选
- separator:分隔符,mybatis会在每次迭代后给sql语句append上separator属性指定的字符,该参数为可选项
- open:表示该语句以什么开始,最常用的是左括弧’(’,注意:mybatis会将该字符拼接到整体的sql语句之前,并且只拼接一次,该参数为可选项
- close:表示该语句以什么开始,最常用的是右括弧’)’,注意:mybatis会将该字符拼接到整体的sql语句之后,并且只拼接一次,该参数为可选项
- index:在list、Set和数组中,index表示当前迭代的位置,在map中,index代指是元素的key,该参数是可选项。
回填主键
useGeneratedKeys="true" keyProperty="id"
<!--回填主键:useGeneratedKeys="true" keyProperty="id" --> <insert id="insertTwo" parameterType="com.mbyte.easy.admin.entity.Student" useGeneratedKeys="true" keyProperty="id"> insert into student (name, img, sex, create_time) values ( #{student.name,jdbcType=VARCHAR}, #{student.img,jdbcType=VARCHAR}, #{student.sex,jdbcType=INTEGER}, #{student.createTime,jdbcType=TIMESTAMP} ) </insert>
// 回填主键,执行完毕之后,student2中id自动赋值 studentMapper.insertTwo(student2); // 直接可以获取到数据库生成的主键id student2.getId(); System.out.println("student2:"+student2);
更新
<!--注意字段判断--> <update id="updateStuddent" > update student <set> <if test="student.name != null"> name = #{student.name,jdbcType=VARCHAR}, </if> <if test="student.img != null"> img = #{student.img,jdbcType=VARCHAR}, </if> <if test="student.sex != null"> sex = #{student.sex,jdbcType=INTEGER}, </if> <if test="student.createTime != null"> create_time = #{student.createTime,jdbcType=TIMESTAMP}, </if> </set> where id = #{student.id,jdbcType=BIGINT} </update>
模糊查询
like '%xxxxxx%' // 数据库语法
- 使用CONCAT拼接(首选)
<if test="article.title != null"> title like CONCAT('%',#{article.title},'%') </if>
- 使用#{...}
title like "%"#{title}"%"
- 使用${...}
name like '%${name}%'
#占位符和$拼接符相关
区别
- #{}采用预编译,防止sql注入,传入数据都会加引号‘,作为参数不作为指令去执行
- select * from user where username ='' and password ='
- 传入:1' or '1'='1' => 处理后:'1\' or \'1\'=\'1\'' 作为一个参数的值而不是命令来执行
- 两侧添加单引号 ''
- 原有单引号转义 ' => \'
- 源码:PreparedStatement#setString
- ${}采用sql拼接,不能防止sql注入
说明
- 不论是单个参数,还是多个参数,一律都建议使用注解@Param("key"),
- xml取#{key}
- 能用 #{} 的地方就用 #{},不用或少用 ${}
- $符号 =》 sql注入
- 表名作参数时,必须用 ${}。如:select * from ${tableName}
- order by 时,必须用 ${}。如:select * from t_user order by ${columnName}
- 使用 ${} 时,要注意何时加或不加单引号
总结
#占位符使用
- where条件后所有参数的获取
- insert /update
- limit xxx,xxx 分页属性的拼接 直接传入页码和条数,不允许计算,
- eg:#{pageNo}-1)*#{pageSize},#{pageSize} 错误的,
- 正确:#{pageNo},#{pageSize};
$拼接使用
- 主要用在sql拼接上
- select xxx from 之间获取字段的拼接
- order by xxxx asc 动态排序字段的拼接
mapper层是否允许方法重载?
- Mapper层方法语法上可以重载,但是重载之后的多个方法对应Xml中的一个Id,Xml中id不可重复;所以要求每个方法的参数都可以和xml中的传参数对应。(但实际使用中目前未使用过Mapper层方法重载)
- 底层:在Mybaits初始化解析所有Xml时,会维护一个Map(Configuration#mappedStatements),key是Xml中的【命名空间+id】(命名空间namespace就是对应Mapper类的全限定名),在进行Mapper层方法调用时,会以所在类的【全限定名+方法名】(和方法的参数无关)为key从mappedStatements中获取对应的MappedStatement,然后执行对应的Sql。
可以进行重载,但重载后多个方法对应一个xml文件中的id,要求每个参数与xml传的参数相对应。mybatis初始化解析xml文件的时候,会维护一个Map(mappedStatements),key是namespace+id ,当mapper层方法调用的时候,会根据【所在类的全限定名+方法名】作为key从mappedStatements中获取MappedStatement,然后执行对应sql
连表查询
一对一、多对一(association)
<select id="listPage1" parameterType="java.lang.Long" resultMap="BaseResultMapOneToOne"> select <include refid="Base_Column_List" /> from student </select>
<resultMap id="BaseResultMapOneToOne" type="com.mbyte.easy.admin.entity.Student"> <id column="id" jdbcType="BIGINT" property="id" /> <id column="class_id" jdbcType="BIGINT" property="classId" /> <id column="name" jdbcType="VARCHAR" property="name" /> <id column="img" jdbcType="VARCHAR" property="img" /> <id column="sex" jdbcType="INTEGER" property="sex" /> <id column="create_time" jdbcType="TIMESTAMP" property="createTime" /> <association property="classInfo" column="class_id" select="com.mbyte.easy.admin.mapper.ClassInfoMapper.getClassInfoById"> </association> </resultMap>
<select id="getClassInfoById" parameterType="java.lang.Long" resultMap="BaseResultMapTest"> select <include refid="Base_Column_List" /> from class_info where id = #{id,jdbcType=BIGINT} </select>
一对多、多对多(collections)
<resultMap id="BaseResultMapStudent" type="com.mbyte.easy.admin.entity.ClassInfo"> <id column="id" jdbcType="BIGINT" property="id" /> <id column="name" jdbcType="VARCHAR" property="name" /> <id column="remark" jdbcType="VARCHAR" property="remark" /> <collection property="studentList" column="id" select="getStudnetByClassId" > </collection> </resultMap>
<select id="getClassInfo" parameterType="java.lang.Long" resultMap="BaseResultMapStudent"> select * from class_info </select>
<select id="getStudnetByClassId" parameterType="java.lang.Long" resultType="com.mbyte.easy.admin.entity.Student"> select * from student where class_id = #{classId,jdbcType=BIGINT} </select>
传递多个参数时示例
collection :
<collection property="checkIndexSumPersonChildList" column="{personId=person_id,checkIndexSumId=check_index_sum_id}" select="getCheckIndexSumPersonChild"/>
<select id="getCheckIndexSumPersonChild" resultType="com.mbyte.easy.admin.entity.CheckIndexSumPersonChild"> select * from check_index_sum_person_child where check_index_sum_id = #{checkIndexSumId} and person_id = #{personId} order by id asc </select>