Spring Mybatis 学习笔记

qaq

配置

配置数据库信息

添加@MapperScan注解

预编译sql语句

#{...}

  • 执行时会将#{...}替换为?,自动设置参数值
  • 参数传递都使用
  • 可以防止sql注入
@Mapper
public interface EmpMapper {
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);
}

${...}

  • 直接将参数拼接在sql语句中,会存在注入问题
  • 如果对表名、列表进行动态设置时使用
@Delete("delete from emp where id = ${id}")

插入

@Mapper
public interface EmpMapper {
    @insert("insert into emp(username, name, gender,image,job,entrydate,dept_id,create_time,update_time) values ('Tom','汤姆',1,'1.jpg',1,'2005-01-01',1,now(),now())")
    public void insert();
}

采用类封装,注意传的参数是类的属性,需要驼峰命名

@Mapper
public interface EmpMapper {
    @insert("insert into emp(username, name, gender,image,job,entrydate,dept_id,create_time,update_time) values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptID},#{createTime},#{updateTime}")
    public void insert(Emp emp);
}

获取主键

会自动将生成的主键值,赋值给emp对象的id属性

@Options(keyProperty="id",useGeneratedKeys=true)
@insert("insert into emp(username, name, gender,image,job,entrydate,dept_id,create_time,update_time) values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptID},#{createTime},#{updateTime}")
public void insert(Emp emp);

更新

@Update("update emp set username = #{username}, name = #{name}, gender = #{gender}, image = #{image}, job = #{job}, entrydate = #{entrydate}, dept_id = #{deptId}, update_time = #{updateTime} where id = #{id}")
public void update(Emp emp);

查询

通过主键

  • 给变量取别名,将下划线命名法映射为驼峰命名
@Select("select id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime, from emp where id = #{id}")
public Emp getById(Integer id);
  • 通过@Results, @Result注解手动映射封装
@Results({
    @Result(column = "dept_id", property = "deptId"),
    @Result(column = "create_time", property = "createTime"),
    @Result(column = "update_time", property = "updateTime")
})
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
  • 开启mybatis的驼峰命名自动映射开关, a_column -> aColumn
//在application.properties中
mybatis.configuration.map-underscore-to-camel-case=true

条件查询

  • name作模糊匹配需要用$而不是#
  • 会有注入问题
@Select("select * from emp where name like '%${name}%' and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc")
public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
  • 可以使用concat函数解决
@Select("select * from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc")
public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);

XML映射文件

  • XML文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)
    • XML文件在resources文件夹下面,和Mapper接口的路径相仿
  • XML文件的namespace属性为Mapper接口全限定名一致
  • XML文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致

Mapper接口:

@Mapper
public interface EmpMapper {
    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
}

XML映射文件:

<mapper namespace="com.itheima.mapper.EmpMapper">
    <select id="list" resultType="com.itheima.pojo.Emp">
        select * from where name like concat('%', #{name}, '%') and gender=#{gender} and entrydate between #{begin} and #{end} order by update_time desc
    </select>
</mapper>

动态sql

  • <if> 用于判断条件是否成立
  • 如果条件为true,则拼接sql
  • <if test="name != null">...</if>
  • <where> 用于动态生成where关键字
  • 如果里面条件都不成立就不生成
  • 可以自动处理里面条件里多余的 and
  • <set> 动态地在行首插入set关键字,删掉额外的逗号
<select id="list" resultType="com.itheima.pojo.Emp">
    select *
    from emp
    <where>
        <if test="name != null">
            name like concat('%', #{name}, '%')
        </if>
        <if test="gender != null">
            and gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and entrydate between #{begin} and #{end}
        </if>
    </where>
    order by update_time desc
</select>

foreach遍历

  • collection:遍历的集合
  • item:遍历出来的元素
  • separator:分隔符
  • open:遍历开始前拼接的sql片段
  • close:遍历结束后拼接的sql片段

SQL语句:

delete from emp where id in (1,2,3);

接口方法:

//批量删除
public void deleteByIds(List<Integer> ids);

XML映射文件

<delete id="deleteByIds">
    delete from emp where id in
    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
</delete>

sql标签

<sql id="01">
    ...<!-- sql语句 -->
</sql>
...

<include refid="01"/><!-- 语句引用 -->
img_show