Mapper

注解

1
2
3
@Mapper
public interface DeptMapper {
}

参数占位符

1
select * from emp where name = #{name}

xml 文件方式编写SQL

位置: resource/和Mapper.java一样的目录结构/同名.xml

入门_MyBatis中文网 :这里可以找到xml样例:

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rc.springdemo1.mapper.EmpMapper">
<select id="list" resultType="com.rc.springdemo1.pojo.Emp">
select *
from emp
</select>
</mapper>

namespace 属性对应 Mapper.java 的位置

<select 的属性也与对应的方法相同

语句结束后不加分号

标签

  • if :条件判断
    • test里为条件判断,可直接使用变量
  • <where :判断是否需要where,后面的代码是否需要删除 and or
  • <set :功能类似与where标签
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!--    条件查询-->
<select id="list" resultType="com.rc.springdemo1.pojo.Emp">
select *
from emp
<where>
<if test="name != null">
name like concat('%', #{name}, '%')
</if>
<if test="name != null">
and gender = #{gender}
</if>
<if test="name != null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc
</select>

foreach

1
2
3
4
5
6
7
8
9
<!--    批量删除员工-->
<delete id="delete">
delete
from emp
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
  • collection
    • 待遍历的内容,与参数名相同
  • item
    • 遍历出来的对象,命名可自定义
  • separator
    • 分隔符
  • open
    • 开始前添加
  • close
    • 结束后添加

注入对象 @Autowired

在 Service 中

1
2
@Autowired
private DeptMapper deptMapper;

数据库操作

注解形式查询操作 @Select("")

在方法上注解 @Select("")

1
2
3
4
5
6
@Mapper
public interface DeptMapper {
@Select("select * from dept")
List<Dept> list();
}

注解式SQL 参数输入

1
public delete

#{} 如果是对象,直接写属性名

返回结果

如果没有查询结果,则返回 null