Mybatis
基础操作
环境准备
删除
SQL语句:
-- 根据ID删除数据
delete
from emp
where id = 16;
接口方法:
//根据ID删除数据
@Delete("delete from emp where id = #{id}")
public void delete(Integer id);
//public int delete(Integer id);
测试:
//根据ID删除
@Test
public void testDelete(){
//int delete = empMapper.delete(16);
//System.out.println(delete);
empMapper.delete(16);
}
注意事项
如果mapper接口方法形参只有一个普通类型的参数,#{...}里面的属性名可以随便写,如:#(id)、#{value}。
预编译SQL
优势
性能更高
更安全(防止SQL注入)
SQL注入是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法。
日志输出
参数占位符
新增
SQL语句:
-- 插入数据
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());
接口方法:
//新增员工
@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);
测试:
//新增员工
@Test
public void testInsert(){
//构造员工对象
Emp emp = new Emp();
emp.setUsername("Tom3");
emp.setName("汤姆3");
emp.setImage("1.jpg");
emp.setGender((short)1);
emp.setJob((short)1);
emp.setEntrydate(LocalDate.of(2000,1,1));
emp.setCreateTime(LocalDateTime.now());
emp.setUpdateTime(LocalDateTime.now());
emp.setDeptId(1);
//执行新增员工信息操作
empMapper.insert(emp);
System.out.println(emp.getId());
}
主键返回
更新
SQL语句:
-- 更新数据
update emp
set username = '',
name='',
gender='',
image='',
job='',
entrydate='',
dept_id='',
update_time=''
where id = 1;
接口方法:
//更新员工
@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);
测试:
//更新员工
@Test
public void testUpdate(){
//构造员工对象
Emp emp = new Emp();
emp.setId(19);
emp.setUsername("Tom1");
emp.setName("汤姆1");
emp.setImage("1.jpg");
emp.setGender((short)1);
emp.setJob((short)1);
emp.setEntrydate(LocalDate.of(2000,1,1));
emp.setUpdateTime(LocalDateTime.now());
emp.setDeptId(1);
//执行更新员工操作
empMapper.update(emp);
}
查询
数据封装
实体类属性名 和 数据库表查询返回的字段名一致,mybatis会自动封装。
如果实体类属性名 和 数据库表查询返回的字段名不一致,不能自动封装。
SQL语句:
-- 根据ID查询员工
select *
from emp
where id = 19;
接口方法:
//方案三: 开启mybatis的驼峰命名自动映射开关 --- a_cloumn ------> aColumn
//根据ID查询员工
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
//方案一: 给字段起别名, 让别名与实体类属性一致
//@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);
测试:
//根据ID查询员工
@Test
public void testGetById(){
Emp emp = empMapper.getById(19);
System.out.println(emp);
}
条件查询
SQL语句:
-- 条件查询员工
select *
from emp
where name like '%张%'
and gender = 1
and entrydate between '2010-01-01' and '2020-01-01'
order by update_time desc;
接口方法:
//条件查询员工
//方式一
//@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);
//方式二
@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);
测试:
//根据条件查询员工
@Test
public void testList(){
//List<Emp> empList = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
//List<Emp> empList = empMapper.list("张", null, null, null);
//List<Emp> empList = empMapper.list("张", (short)1, null, null);
//List<Emp> empList = empMapper.list(null, (short)1, null, null);
List<Emp> empList = empMapper.list(null, null, null, null);
System.out.println(empList);
}
XML映射文件
动态SQL
if
<if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。
<where>:where 元素只会在子元素有内容的情况下才插入where子句。而且会自动去除子句的开头的AND 或OR。
<select id="list" resultType="com.itheima.pojo.Emp">
<include refid="commonSelect"/>
<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>
案例
完善更新员工功能,修改为动态更新员工数据信息
<set>:动态地在行首插入 SET 关键字,并会删掉额外的逗号。(用在update语句中)
<!-- 动态更新员工-->
<update id="update2">
update emp
<set>
<if test="username != null">username = #{username},</if>
<if test="name != null">name = #{name},</if>
<if test="gender != null">gender = #{gender},</if>
<if test="image != null">image = #{image},</if>
<if test="job != null">job = #{job},</if>
<if test="entrydate != null">entrydate = #{entrydate},</if>
<if test="deptId != null">dept_id = #{deptId},</if>
<if test="updateTime != null">update_time = #{updateTime}</if>
</set>
where id = #{id}
</update>
foreach
接口方法:
//批量删除员工
public void deleteByIds(List<Integer> ids);
XML映射文件:
<!--批量删除员工 (18,19,20)-->
<!--
collection: 遍历的集合
item: 遍历出来的元素
separator: 分隔符
open: 遍历开始前拼接的SQL片段
close: 遍历结束后拼接的SQL片段
-->
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
sql&include
<sql>:定义可重用的 SQL 片段。
<include>:通过属性refid,指定包含的sql片段。
<sql id="commonSelect">
select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time
from emp
</sql>
<select id="list" resultType="com.itheima.pojo.Emp">
<include refid="commonSelect"/>
<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>