1、建库建表
create database `mybatis-example`;
use `mybatis-example`;
create table emp
(
empNo varchar(40),
empName varchar(100),
sal int,
deptno varchar(10)
);
insert into emp values('e001','张三',8000,'d001');
insert into emp values('e002','李四',9000,'d001');
insert into emp values('e003','王五',10000,'d001');
insert into emp values('e004','赵六',11000,'d002');
insert into emp values('e005','田七',12000,'d002');
insert into emp values('e006','周八',13000,'d003');
insert into emp values('e007','吴九',14000,'d004');
insert into emp values('e008','郑十',15000,'d004');
insert into emp values('d8f9b794-95ba-11ee-ab75-84a93ea22bfb','张三丰',16000,'d001');
2、pom.xml
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<!-- MySQL驱动 mybatis底层依赖jdbc驱动实现,本次不需要导入连接池,mybatis自带! -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--junit5测试-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 日志 , 会自动传递slf4j门面-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
</dependencies>
3、Emp.java
package com.atguigu.mybatis.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private String empNo;
private Integer sal;
private String empName;
private String deptno;
}
4、com/atguigu/mybatis/mappper/EmpMapper.java
package com.atguigu.mybatis.mapper;
import com.atguigu.mybatis.pojo.Emp;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface EmpMapper {
//1.演示where-if标签
List<Emp> getEmpList(Emp emp);
//2、演示set标签
void updateEmp(Emp emp);
//3、演示trim标签
List<Emp> getEmpList2(Emp emp);
//4、演示choose/when/otherwise标签
List<Emp> getEmpList3(Emp emp);
//5、演示foreach标签
List<Emp> getEmpList4(@Param("empNoList") List<String> empNoList);
}
5、mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 具体配置 -->
<!-- 从org.apache.ibatis.session.Configuration类中可以查看能使用的配置项 -->
<!-- 将mapUnderscoreToCamelCase属性配置为true,表示开启自动映射驼峰式命名规则 -->
<!-- 规则要求数据库表字段命名方式:单词_单词 -->
<!-- 规则要求Java实体类属性名命名方式:首字母小写的驼峰式命名 -->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="autoMappingBehavior" value="FULL"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<!--<typeAlias type="com.atguigu.mybatis.pojo.Employee" alias="emp"/>-->
<package name="com.atguigu.mybatis.pojo"/>
</typeAliases>
<!-- environments表示配置Mybatis的开发环境,可以配置多个环境,在众多具体环境中,使用default属性指定实际运行时使用的环境。default属性的取值是environment标签的id属性的值。 -->
<environments default="development">
<!-- environment表示配置Mybatis的一个具体的环境 -->
<environment id="development">
<!-- Mybatis的内置的事务管理器 -->
<transactionManager type="JDBC"/>
<!-- 配置数据源 -->
<dataSource type="POOLED">
<!-- 建立数据库连接的具体信息 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- Mapper注册:指定Mybatis映射文件的具体位置 -->
<!-- mapper标签:配置一个具体的Mapper映射文件 -->
<!-- resource属性:指定Mapper映射文件的实际存储位置,这里需要使用一个以类路径根目录为基准的相对路径 -->
<!-- 对Maven工程的目录结构来说,resources目录下的内容会直接放入类路径,所以这里我们可以以resources目录为基准 -->
<!--<mapper resource="mappers/EmpMapper.xml"/>-->
<package name="com.atguigu.mybatis.mapper"/>
</mappers>
</configuration>
6、com/atguigu/mybatis/mappper/EmpMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace等于mapper接口类的全限定名,这样实现对应 -->
<mapper namespace="com.atguigu.mybatis.mapper.EmpMapper">
<select id="getEmpList" resultType="Emp">
select * from emp
<where>
<if test="empNo!= null">
empNo=#{empNo}
</if>
<if test="empName!= null">
and empName=#{empName}
</if>
<if test="sal!=null">
and sal < #{sal}
</if>
<if test="deptno!=null">
and deptno=#{deptno}
</if>
</where>
<!--
select * from emp
select * from emp WHERE empNo=?
select * from emp WHERE sal < ?
select * from emp WHERE empName=?
select * from emp WHERE deptno=?
select * from emp WHERE empNo=? and sal < ?
select * from emp WHERE empNo=? and empName=? and sal < ?
select * from emp WHERE empNo=? and empName=? and sal < ? and deptno=?
-->
</select>
<update id="updateEmp">
update emp
<set>
<if test="empName!=null">
empName=#{empName},
</if>
<if test="sal!=null">
sal=#{sal},
</if>
<if test="deptno!=null">
deptno=#{deptno}
</if>
</set>
where empNo=#{empNo}
<!--
update emp SET empName=?, sal=?, deptno=? where empNo=?
update emp SET empName=? where empNo=?
update emp where empNo=?
-->
</update>
<select id="getEmpList2" resultType="Emp">
select * from emp
<trim prefix="where" suffix=";" prefixOverrides="or|and" suffixOverrides="or">
<if test="empNo!=null">
or empNo=#{empNo} or
</if>
<if test="empName!=null">
or empName=#{empName} or
</if>
<if test="sal!=null">
or sal < #{sal} or
</if>
<if test="deptno!=null">
or deptno=#{deptno} or
</if>
</trim>
</select>
<select id="getEmpList3" resultType="Emp">
select * from emp where
<choose>
<when test="empNo!=null">
empNo=#{empNo}
</when>
<when test="empName!=null">
empName=#{empName}
</when>
<when test="sal!=null">
sal < #{sal}
</when>
<when test="deptno!=null">
deptno=#{deptno}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</select>
<select id="getEmpList4" resultType="Emp">
<include refid="allColumns"></include>
from emp where empNo in
<foreach collection="empNoList" item="employeeNumber" open="(" close=")" separator=",">
#{employeeNumber}
</foreach>
</select>
<sql id="allColumns">
select empNo,empName,sal,deptno,'China' as 'address'
</sql>
</mapper>
7、logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置,ConsoleAppender表示输出到控制台 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 日志输出的格式 -->
<!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 设置全局日志级别。日志级别按顺序分别是:TRACE、DEBUG、INFO、WARN、ERROR -->
<!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!-- 根据特殊需求指定局部日志级别,可以是包名或全类名。 -->
<logger name="com.atguigu.mybatis" level="DEBUG" />
</configuration>
8、MybatisTest.java
package mybatis;
import com.atguigu.mybatis.mapper.EmpMapper;
import com.atguigu.mybatis.pojo.Emp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class MybatisTest {
SqlSessionFactory sqlSessionFactory;
SqlSession sqlSession;
EmpMapper empMapper;
@BeforeEach
public void setup() throws IOException {
// 获取资源流,读取"mybatis-config.xml"文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 使用资源流创建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 使用SqlSessionFactory打开一个Session
sqlSession = sqlSessionFactory.openSession();
//基于Mapper接口编程
empMapper=sqlSession.getMapper(EmpMapper.class);
}
// 在每个测试用例之后执行的清理方法
@AfterEach
public void teardown() {
sqlSession.commit(); // 提交事务
sqlSession.close(); // 关闭SqlSession
}
@Test
public void selectWhereIFTest() {
/**
* 1、所有条件都不满足
*/
Emp emp = new Emp();
empMapper.getEmpList(emp).forEach(System.out::println);//select * from emp
//Emp(empNo=e001, sal=8000, empName=张三, deptno=d001)
//Emp(empNo=e002, sal=9000, empName=李四, deptno=d001)
//Emp(empNo=e003, sal=10000, empName=王五, deptno=d001)
//Emp(empNo=e004, sal=11000, empName=赵六, deptno=d002)
//Emp(empNo=e005, sal=12000, empName=田七, deptno=d002)
//Emp(empNo=e006, sal=13000, empName=周八, deptno=d003)
//Emp(empNo=e007, sal=14000, empName=吴九, deptno=d004)
//Emp(empNo=e008, sal=15000, empName=郑十, deptno=d004)
//Emp(empNo=d8f9b794-95ba-11ee-ab75-84a93ea22bfb, sal=16000, empName=张三丰, deptno=d001)
/**
* 2、一个条件满足
*/
Emp emp1 = new Emp();
emp1.setEmpNo("e002");
empMapper.getEmpList(emp1).forEach(System.out::println);//select * from emp WHERE empNo=?
//Emp(empNo=e002, sal=9000, empName=李四, deptno=d001)
Emp emp2 = new Emp();
emp2.setSal(11000);
empMapper.getEmpList(emp2).forEach(System.out::println);//select * from emp WHERE sal < ?
//Emp(empNo=e001, sal=8000, empName=张三, deptno=d001)
//Emp(empNo=e002, sal=9000, empName=李四, deptno=d001)
//Emp(empNo=e003, sal=10000, empName=王五, deptno=d001)
Emp emp3 = new Emp();
emp3.setEmpName("张三丰");
empMapper.getEmpList(emp3).forEach(System.out::println);//select * from emp WHERE empName=?
//Emp(empNo=d8f9b794-95ba-11ee-ab75-84a93ea22bfb, sal=16000, empName=张三丰, deptno=d001)
Emp emp4 = new Emp();
emp4.setDeptno("d001");
empMapper.getEmpList(emp4).forEach(System.out::println);//select * from emp WHERE deptno=?
//Emp(empNo=e001, sal=8000, empName=张三, deptno=d001)
//Emp(empNo=e002, sal=9000, empName=李四, deptno=d001)
//Emp(empNo=e003, sal=10000, empName=王五, deptno=d001)
//Emp(empNo=d8f9b794-95ba-11ee-ab75-84a93ea22bfb, sal=16000, empName=张三丰, deptno=d001)
/**
* 2、两个条件满足
*/
Emp emp5 = new Emp();
emp5.setEmpNo("e002");
emp5.setSal(11000);
empMapper.getEmpList(emp5).forEach(System.out::println);//select * from emp WHERE empNo=? and sal <?
//Emp(empNo=e002, sal=9000, empName=李四, deptno=d001)
/**
* 3、三个条件都满足,以次类推
*/
Emp emp6 = new Emp();
emp6.setEmpNo("e002");
emp6.setSal(11000);
emp6.setEmpName("张三丰");
empMapper.getEmpList(emp6).forEach(System.out::println);//select * from emp WHERE empNo=? and empName=? and sal < ?
/**
* 4、全部条件满足
*/
Emp emp100 = new Emp("e001",8001,"张三","d001");
empMapper.getEmpList(emp100).forEach(System.out::println);//select * from emp WHERE empNo=? and empName=? and sal < ? and deptno=?
//Emp(empNo=e001, sal=8000, empName=张三, deptno=d001)
}
@Test
public void updateSetIfTest() {
/**
* 1、所有条件都满足
*/
Emp emp = new Emp("e001",4000,"张三","d001");
empMapper.updateEmp(emp);//update emp SET empName=?, sal=?, deptno=? where empNo=?
/**
* 2、部分条件满足
*/
Emp emp1 = new Emp();
emp1.setEmpNo("e002");
emp1.setEmpName("张无忌");
empMapper.updateEmp(emp1);//update emp SET empName=? where empNo=?
/**
* 3、所有条件都不满足,报错SQLSyntaxErrorException
*/
Emp emp2 = new Emp();
emp2.setEmpNo("e003");
empMapper.updateEmp(emp2);
}
@Test
public void trimTest() {
Emp emp = new Emp();
empMapper.getEmpList2(emp).forEach(System.out::println);//select * from emp
Emp emp1 = new Emp();
emp1.setEmpNo("e001");
empMapper.getEmpList2(emp1).forEach(System.out::println);//select * from emp where empNo=? ;
}
@Test
public void chooseWhenTest() {
Emp emp1 = new Emp();
empMapper.getEmpList3(emp1).forEach(System.out::println);//select * from emp where 1=1
Emp emp2 = new Emp();
emp2.setEmpNo("e001");
empMapper.getEmpList3(emp2).forEach(System.out::println);//select * from emp where empNo=?
Emp emp3 = new Emp();
emp3.setEmpNo("e002");
emp3.setEmpNo("李四");
empMapper.getEmpList3(emp3).forEach(System.out::println);//select * from emp where empNo=?
}
@Test
public void foreachTest() {
Emp emp = new Emp();
empMapper.getEmpList4(Arrays.asList("e001","e002")).forEach(System.out::println);
//select * from emp where empNo in ( ? , ? )
//Emp(empNo=e001, sal=4000, empName=张三, deptno=d001)
//Emp(empNo=e002, sal=9000, empName=李四, deptno=d001)
}
}