官网:https://mybatis.org/mybatis-3/zh/index.html
一.Mybatis入门
1.快速入门
2.JDBC介绍
3.数据库连接池
官方地址:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
4.lombok
二.Mybatis基础增删改查
1.准备
2.删除
3.新增
4.更新
5.查询
# 配置数据库的连接信息 - 四要素
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234
# 配置mybatis的日志信息,指定到输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#开启mybatis的驼峰命名自动映射开关
mybatis.configuration.map-underscore-to-camel-case=true
package com.wjh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private Integer id;
private String username;
private String password;
private String name;
private Short gender;
private String image;
private Short job;
private LocalDate entrydate;
private Integer deptId;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
package com.wjh.mapper;
import com.wjh.pojo.Emp;
import org.apache.ibatis.annotations.*;
import java.time.LocalDate;
import java.util.List;
@Mapper
public interface EmpMapper {
//查询所有员工信息
@Select("select * from emp")
public List<Emp> select();
//根据ID删除员工信息操作
@Delete("delete from emp where id = #{id}")
//public void delete(Integer id);
public int delete(Integer id);
//新增员工
@Options(useGeneratedKeys = true, keyProperty = "id")
@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);
//根据id查询用户信息
@Select("select * from emp where id = #{id}")
public Emp selectId(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 selectId2(Integer id);
//
// //方案二: 通过#@Result注解手动映射
// @Results({
// @Result(column = "dept_id",property = "deptId"),
// @Result(column = "create_time",property = "createTome"),
// @Result(column = "update_time",property = "updateTime")
// })
// @Select("select * from emp where id = #{id}")
// public Emp selectId3(Integer id);
//方案三: 开启mybatis的驼峰命名自动映射开关 -- a_column --------> aColumn
//条件查询员工信息
@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 );
// select concat('hello', 'mysql', 'word');
// select * from emp where name like concat('%', '张', '%') and gender = '1' and
// entrydate between '2010-01-01' and '2020-01-01' order by update_time desc;
}
package com.wjh;
import com.wjh.mapper.EmpMapper;
import com.wjh.pojo.Emp;
import org.apache.ibatis.annotations.Mapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
@Autowired
private EmpMapper EmpMapper;
//查询所有员工测试类
@Test
public void testListEmp(){
List<Emp> empList = EmpMapper.select();
empList.stream().forEach(selectEmp -> {
System.out.println(selectEmp);
});
}
//根据id删除员工信息测试类
@Test
public void testDelete(){
EmpMapper.delete(4);
//int delete = EmpMapper.delete(4);
//System.out.println("删除了" + delete + "条数据");
testListEmp();
}
//新增员工测试类
@Test
public void testInsert(){
Emp empInsert = new Emp();
empInsert.setUsername("ikun6");
empInsert.setName("坤坤6");
empInsert.setGender((short)2);
empInsert.setImage("#");
empInsert.setJob((short)1);
empInsert.setEntrydate(LocalDate.of(2000,01,01));
empInsert.setDeptId(1);
empInsert.setCreateTime(LocalDateTime.now());
empInsert.setUpdateTime(LocalDateTime.now());
//执行员工信息操作
EmpMapper.insert(empInsert);
System.out.println("主键:" + empInsert.getId());
}
//修改员工信息测试类
@Test
public void testUpdate(){
Emp empUpdate = new Emp();
empUpdate.setId(10);
empUpdate.setUsername("zhaomingming");
empUpdate.setName("赵敏");
empUpdate.setGender((short)1);
empUpdate.setImage("#");
empUpdate.setJob((short)1);
empUpdate.setEntrydate(LocalDate.of(2000,01,01));
empUpdate.setDeptId(1);
empUpdate.setUpdateTime(LocalDateTime.now());
//执行员工信息操作
EmpMapper.update(empUpdate);
}
//根据id查询用户信息测试类
@Test
public void testSelectId(){
Emp emp = EmpMapper.selectId(10);
System.out.println(emp);
}
//根据条件查询员工
@Test
public void testSelect(){
EmpMapper.list("张", (short) 1, LocalDate.of(2010, 01, 01), LocalDate.of(2020, 01 , 01));
}
}
三.Mybatis动态SQL
1.XML映射文件
//条件查询员工信息
public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
<?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.wjh.mapper.EmpMapper">
<!-- resultType:单条记录所封装的类型 -->
<select id="list" resultType="com.wjh.pojo.Emp">
select *
from emp
where name like concat('%', #{name}, '%')
and gender = #{gender}
and entrydate between #{begin} and #{end}
order by update_time desc
</select>
</mapper>
//根据条件查询员工
@Test
public void testSelect(){
List<Emp> empList = EmpMapper.list("张", (short) 1,
LocalDate.of(2010, 01, 01),
LocalDate.of(2020, 01 , 01));
System.out.println(empList);
}
官方说明https://mybatis.net.cn/getting-started.html
2.动态SQL
(1).<if>
<select id="list" resultType="com.wjh.pojo.Emp">
<!-- resultType:单条记录所封装的类型-->
<!-- select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time-->
<!-- from emp-->
<!-- where-->
<!-- <if test="name != null">-->
<!-- name like concat('%', #{name}, '%')-->
<!-- </if>-->
<!-- and gender = #{gender}-->
<!-- and entrydate between #{begin} and #{end}-->
<!-- order by update_time desc-->
<!-- ===============================动态SQL=======================-->
<!-- if -->
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>
//动态更新员工信息(修改)
//@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 update2(Emp emp);
<!-- 动态更新员工信息(修改) -->
<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>
//动态更新员工信息-- 跟新id = 18 的员工 username 为 Tom11,name = 汤姆111, gander更新为2
@Test
public void testUpdate2(){
//构造员工对象
Emp emp = new Emp();
emp.setId(19);
emp.setUsername("tanmgu11");
emp.setName("汤姆111");
emp.setGender((short) 2);
emp.setUpdateTime(LocalDateTime.now());
//执行员工操作
EmpMapper.update2(emp);
}
(2).<foreach>
//批量删除员工
public void deleteByIds(List<Integer> ids);
<!--批量删除员工信息 (22,23,24)-->
<!--
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>
//批量删除员工
@Test
public void testdeleteByIds(){
List<Integer> list = Arrays.asList(16,17,18);
EmpMapper.deleteByIds(list);
}
(3).<sql><include>
<?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.wjh.mapper.EmpMapper">
<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.wjh.pojo.Emp">
<!-- resultType:单条记录所封装的类型-->
<!-- select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time-->
<!-- from emp-->
<!-- where-->
<!-- <if test="name != null">-->
<!-- name like concat('%', #{name}, '%')-->
<!-- </if>-->
<!-- and gender = #{gender}-->
<!-- and entrydate between #{begin} and #{end}-->
<!-- order by update_time desc-->
<!-- ===============================动态SQL=======================-->
-- if
<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>
<!-- 动态更新员工信息(修改) -->
<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>
<!--批量删除员工信息 (22,23,24)-->
<!--
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>
</mapper>