概念:
根据不同的状况生成不同的SQL语句。
关键字:if,choose(when,otherwise),trim(where,set),foreach
.
搭建环境:
- 数据库:
CREATE TABLE book(id INT(10) PRIMARY KEY COMMENT '书id',
NAME VARCHAR(50) NOT NULL COMMENT '书名',
author VARCHAR(20) NOT NULL COMMENT '作者',
TIME DATETIME NOT NULL COMMENT '发布时间',
seal INT(30) NOT NULL COMMENT '销量'
)ENGINE=INNODB DEFAULT CHARSET=utf8;
- 新建一个模块:
实体类:
import lombok.Data;
import java.util.Date;
/**
* @author jitwxs
* @date 2021年04月06日 14:46
*/
@Data
public class Book {
private int id;
private String name;
private String author;
private Date time;
private int seal;
}
接口:
import pojo.Book;
public interface BookMapper {
//插入数据
int addBook(Book book);
}
编写xml配置文件:
<?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">
<!--namespace=绑定一个对应的dao借口/mapper接口-->
<mapper namespace="dao.BookMapper">
<insert id="addBook" parameterType="Book">
insert into book(id,name,author,time,seal) values (#{id},#{name},#{author},#{time},#{seal})
</insert>
</mapper>
编写IDUtils:
public class IdUtils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-",".");
}}
插入数据:
import org.apache.ibatis.session.SqlSession;
import pojo.Book;
import utils.IdUtils;
import utils.MyBatisUtils;
import java.util.Date;
/**
* @author jitwxs
* @date 2021年04月05日 20:04
*/
public class Test {
@org.junit.Test
public void test(){
SqlSession sqlSession=MyBatisUtils.getSqlSession();
BookMapper bookMapper=sqlSession.getMapper(BookMapper.class);
Book book=new Book();
book.setId(IdUtils.getId());
book.setName("三国");
book.setAuthor("罗贯中");
book.setTime(new Date());
book.setSeal(999);
bookMapper.addBook(book);
book.setId(IdUtils.getId());
book.setName("C++");
bookMapper.addBook(book);
book.setId(IdUtils.getId());
book.setName("Java");
bookMapper.addBook(book);
book.setId(IdUtils.getId());
book.setName("微服务");
bookMapper.addBook(book);
sqlSession.close();
}
}
IF判断:
需求
:查询书籍 如果输入书名,则根据书名查询,如果输入作者则根据作者查询,如果什么都没有输入,则查询所有。编写接口
:
List<Book> queryBookByIf(Map map);
编写xml配置文件
:
<select id="queryBookByIf" parameterType="map" resultType="Book">
select * from book
<where>
<if test="name!=null">
and name=#{name}
</if>
<if test="author!=null">
and author=#{author}
</if>
</where>
测试:
1、什么都不输入
:
@org.junit.Test
public void testIf(){
SqlSession sqlSession=MyBatisUtils.getSqlSession();
BookMapper bookMapper=sqlSession.getMapper(BookMapper.class);
HashMap map=new HashMap();
List<Book> bookList= bookMapper.queryBookByIf(map);
for (Book book : bookList) {
System.out.println(book);
}
sqlSession.close();
}
测试结果:
2、输入作者
: