1. 动态sql
延续前篇博文,进行mybatis动态sql,自己书写方法进行测试
BookMapper类中新增方法
根据id查询
鼠标选中方法名按Alt+Enter键进行自动生成实现
<select id="selectBooksIn" resultType="com.tanle.model.Book" parameterType="java.util.List">
select * from t_mvc_book where bid in
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
去service实现 选中按Alt+Enter键实现生成
BookServiceImpl中通过bookMapper调取
测试类
模糊查询
在BookMapper书写以下三种方式查询
#{...}
${...}
Concat
注意:#{...}自带引号,${...}有sql注入的风险
三种不能的查询语句
再去BookService中调取 同样是Alt+Enter建生成
测试类
这里所使用的到的工具类StringUtils为了模糊查询拼接%%
第三种模糊查询方式不需要通过这个拼接 Concat
package com.tanle.util;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-10-15 18:24
*/
public class StringUtils {
public static String toLinkeStr(String str){
return "%"+str+"%";
}
}
查询返回结果集的处理
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
使用resultMap返回自定义类型集合
使用resultType返回List
使用resultType返回单个对象
使用resultType返回List
书写一个BookVo实体类
mybatis hibernate都是orm框架,表所存在的列段在实体类model都有映射
实际开发中,会因为某一些需求改变model 破坏model的封装性
此时为了保证Model的封装性,就可以使用vo类来完成指定的需求
package com.tanle.model.vo;
import com.tanle.model.Book;
import java.util.List;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-10-15 18:40
*
*
* vo介绍
* mybatis hibernate都是orm框架,表所存在的列段在实体类model都有映射
* 实际开发中,会因为某一些需求改变model 破坏model的封装性
* 此时为了保证Model的封装性,就可以使用vo类来完成指定的需求
*
*/
public class BookVo extends Book {
private Integer min;
private Integer max;
private List<Integer> bookIds;
public Integer getMin() {
return min;
}
public void setMin(Integer min) {
this.min = min;
}
public Integer getMax() {
return max;
}
public void setMax(Integer max) {
this.max = max;
}
public List<Integer> getBookIds() {
return bookIds;
}
public void setBookIds(List<Integer> bookIds) {
this.bookIds = bookIds;
}
}
service
2. 分页查询
为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的
使用分页插件步奏
1、导入pom依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
2、Mybatis.cfg.xml配置拦截器
<plugins>
<!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
3、使用PageHelper进行分页
<select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>
Mapper层
List<Map> listPager(Map map);
Service层
List<Map> listPager(Map map, PageBean pageBean);
BookServiceImpl实现层
@Override
public List<Map> listPager(Map map, PageBean pageBean) {
if(pageBean != null && pageBean.isPagination()){
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
}
List<Map> list = bookMapper.listPager(map);
if(pageBean != null && pageBean.isPagination()){
PageInfo pageInfo = new PageInfo(list);
System.out.println("页码:"+pageInfo.getPageNum());
System.out.println("页大小:"+pageInfo.getPageSize());
System.out.println("总记录:"+pageInfo.getTotal());
pageBean.setTotal(pageInfo.getTotal()+"");
}
return list;
}
PageBean工具类
package com.tanle.util;
import java.io.Serializable;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class PageBean implements Serializable {
private static final long serialVersionUID = 2422581023658455731L;
//页码
private int page=1;
//每页显示记录数
private int rows=10;
//总记录数
private int total=0;
//是否分页
private boolean isPagination=true;
//上一次的请求路径
private String url;
//获取所有的请求参数
private Map<String,String[]> map;
public PageBean() {
super();
}
//设置请求参数
public void setRequest(HttpServletRequest req) {
String page=req.getParameter("page");
String rows=req.getParameter("rows");
String pagination=req.getParameter("pagination");
this.setPage(page);
this.setRows(rows);
this.setPagination(pagination);
this.url=req.getContextPath()+req.getServletPath();
this.map=req.getParameterMap();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getMap() {
return map;
}
public void setMap(Map<String, String[]> map) {
this.map = map;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if(null!=page&&!"".equals(page.trim()))
this.page = Integer.parseInt(page);
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public void setRows(String rows) {
if(null!=rows&&!"".equals(rows.trim()))
this.rows = Integer.parseInt(rows);
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return isPagination;
}
public void setPagination(boolean isPagination) {
this.isPagination = isPagination;
}
public void setPagination(String isPagination) {
if(null!=isPagination&&!"".equals(isPagination.trim()))
this.isPagination = Boolean.parseBoolean(isPagination);
}
/**
* 获取分页起始标记位置
* @return
*/
public int getStartIndex() {
//(当前页码-1)*显示记录数
return (this.getPage()-1)*this.rows;
}
/**
* 末页
* @return
*/
public int getMaxPage() {
int totalpage=this.total/this.rows;
if(this.total%this.rows!=0)
totalpage++;
return totalpage;
}
/**
* 下一页
* @return
*/
public int getNextPage() {
int nextPage=this.page+1;
if(this.page>=this.getMaxPage())
nextPage=this.getMaxPage();
return nextPage;
}
/**
* 上一页
* @return
*/
public int getPreivousPage() {
int previousPage=this.page-1;
if(previousPage<1)
previousPage=1;
return previousPage;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
+ "]";
}
}
4、处理分页结果
@Test
public void listPager() {
Map map=new HashMap();
map.put("bname","%圣墟%");
PageBean pageBean=new PageBean();
//不分页
//pageBean.setPagination(false);
//第二页
pageBean.setPage(2);
List<Map> maps = this.bookService.listPager(map, pageBean);
for (Map map1 : maps) {
System.out.println(map1);
}
}
3. 特殊字符处理
>(>)
<(<)
&(&)
空格( )
<![CDATA[ <= ]]>
4. 代码块
BookServiceTest 测试类代码块
package com.tanle.service;
import com.sun.javafx.collections.MappingChange;
import com.tanle.mapper.BookMapper;
import com.tanle.model.Book;
import com.tanle.model.vo.BookVo;
import com.tanle.service.impl.BookServiceImpl;
import com.tanle.util.PageBean;
import com.tanle.util.SessionUtil;
import com.tanle.util.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-10-13 15:57
*/
public class BookServiceTest {
//测试bookService接口是否有用
//先测试不为空
private BookService bookService;
private SqlSession sqlSession;
@Before
public void setUp() throws Exception {
BookServiceImpl bookServiceImpl = new BookServiceImpl();
sqlSession = SessionUtil.openSession();
bookServiceImpl.setBookMapper(sqlSession.getMapper(BookMapper.class));
this.bookService = bookServiceImpl;
}
@After
public void tearDown() throws Exception {
sqlSession.commit();
sqlSession.close();
}
@Test
public void insert() {
Book book = new Book();
book.setBname("mybatis插入");
book.setPrice(99f);
int insert = bookService.insert(book);
System.out.println(insert);
}
@Test
public void selectByPrimaryKey() {
Book book = bookService.selectByPrimaryKey(27);
System.out.println(book.toString());
}
@Test
public void selectBooksIn() {
List list=new ArrayList();
list.add(19);
list.add(18);
list.add(99);
List<Book> books = this.bookService.selectBooksIn(list);
for (Book book : books) {
System.out.println(book);
}
}
/*
* #和$的区别
* #号相当于单引号拼接执行sql
* select * from t_mvc_book where bname like '%圣墟%'
* $会引起sql攻击
* */
@Test
public void selectBooksI1() {
String bname="圣墟";
//第一种根据工具类拼接%进行模糊查询
List<Book> books = this.bookService.selectBooksIn1(StringUtils.toLinkeStr(bname));
//List<Book> books = this.bookService.selectBooksIn2(StringUtils.toLinkeStr(bname));
//List<Book> books = this.bookService.selectBooksIn3(bname);
for (Book book : books) {
System.out.println(book);
}
}
@Test
public void list() {
// List<Book> books = this.bookService.list1();
// List<Book> books = this.bookService.list2();
List list=new ArrayList();
list.add(15);
list.add(18);
list.add(99);
/* BookVo bookVo=new BookVo();
bookVo.setBookIds(list);
List<Book> books = this.bookService.list3(bookVo);*/
/* for (Book book : books) {
System.out.println(book);
}*/
Map map=new HashMap();
/*map.put("bookIds",list);
List<Map> books = this.bookService.list4(map);
for (Map book : books) {
System.out.println(book);
}*/
map.put("bid",19);
Map map1 = this.bookService.list5(map);
System.out.println(map1);
}
@Test
public void listPager() {
Map map=new HashMap();
map.put("bname","%圣墟%");
PageBean pageBean=new PageBean();
//不分页
//pageBean.setPagination(false);
//第二页
pageBean.setPage(2);
List<Map> maps = this.bookService.listPager(map, pageBean);
for (Map map1 : maps) {
System.out.println(map1);
}
}
@Test
public void list6() {
BookVo bookVo=new BookVo();
bookVo.setMin(2);
bookVo.setMax(20);
List<Book> books = bookService.list6(bookVo);
for (Book book : books) {
System.out.println(book);
}
}
}
BookMapper
package com.tanle.mapper;
import com.tanle.model.Book;
import com.tanle.model.vo.BookVo;
import com.tanle.util.PageBean;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface BookMapper {
int deleteByPrimaryKey(Integer bid);
int insert(Book record);
int insertSelective(Book record);
Book selectByPrimaryKey(Integer bid);
int updateByPrimaryKeySelective(Book record);
int updateByPrimaryKey(Book record);
/*
* Param
* 如果形参要在mapper.xml中使用就需要加上面注解
* map name:zs age:12
* @param bookIds
*
* */
List<Book> selectBooksIn(@Param("bookIds") List bookIds);
List<Book> selectBooksIn1(@Param("bname") String bname);
List<Book> selectBooksIn2(@Param("bname") String bname);
List<Book> selectBooksIn3(@Param("bname") String bname);
/*
* mybatis结果集处理的五种情况
* */
List<Book> list1();
List<Book> list2();
List<Book> list3(BookVo bookVo);
List<Map> list4(Map map);
Map list5(Map map);
/*、
* 分页
* */
List<Map> listPager(Map map);
/*
* mybatis特殊字符处理
* 第一种写法
* select * from t_mvc_book where price >#{min} and price <#{max}
* 第二种包含
* select * from t_mvc_book where <![CDATA[ price > #{min} and price < #{max}]]>
* * */
List<Book> list6(BookVo bookVo);
}
BookMapper.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" >
<mapper namespace="com.tanle.mapper.BookMapper" >
<resultMap id="BaseResultMap" type="com.tanle.model.Book" >
<constructor >
<idArg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="bname" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
bid, bname, price
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_mvc_book
where bid = #{bid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_mvc_book
where bid = #{bid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.tanle.model.Book" >
insert into t_mvc_book (bid, bname, price
)
values (#{bid,jdbcType=INTEGER}, #{bname,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
)
</insert>
<insert id="insertSelective" parameterType="com.tanle.model.Book" >
insert into t_mvc_book
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="bid != null" >
bid,
</if>
<if test="bname != null" >
bname,
</if>
<if test="price != null" >
price,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="bid != null" >
#{bid,jdbcType=INTEGER},
</if>
<if test="bname != null" >
#{bname,jdbcType=VARCHAR},
</if>
<if test="price != null" >
#{price,jdbcType=REAL},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.tanle.model.Book" >
update t_mvc_book
<set >
<if test="bname != null" >
bname = #{bname,jdbcType=VARCHAR},
</if>
<if test="price != null" >
price = #{price,jdbcType=REAL},
</if>
</set>
where bid = #{bid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.tanle.model.Book" >
update t_mvc_book
set bname = #{bname,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL}
where bid = #{bid,jdbcType=INTEGER}
</update>
<!--
Foreach
resultType 返回对象
parameterType 返回参数
collection 接收传过来的变量
item 取名
-->
<select id="selectBooksIn" resultType="com.tanle.model.Book" parameterType="java.util.List">
select * from t_mvc_book where bid in
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
<select id="selectBooksIn1" resultType="com.tanle.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like #{bname}
</select>
<select id="selectBooksIn2" resultType="com.tanle.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectBooksIn3" resultType="com.tanle.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>
<select id="list1" resultMap="BaseResultMap">
select * from t_mvc_book
</select>
<select id="list2" resultType="com.tanle.model.Book">
select * from t_mvc_book
</select>
<select id="list3" resultType="com.tanle.model.Book" parameterType="com.tanle.model.vo.BookVo">
select * from t_mvc_book where bid in
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
<select id="list4" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bid in
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
<select id="list5" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bid = #{bid}
</select>
<select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>
<select id="list6" resultType="com.tanle.model.Book" parameterType="com.tanle.model.vo.BookVo">
select * from t_mvc_book where <![CDATA[ price > #{min} and price < #{max}]]>
</select>
</mapper>
BookServiceImpl
package com.tanle.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tanle.mapper.BookMapper;
import com.tanle.model.Book;
import com.tanle.model.vo.BookVo;
import com.tanle.service.BookService;
import com.tanle.util.PageBean;
import java.util.List;
import java.util.Map;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-10-13 14:11
*/
public class BookServiceImpl implements BookService {
//依赖于Bookmapper
private BookMapper bookMapper;
public BookMapper getBookMapper() {
return bookMapper;
}
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int deleteByPrimaryKey(Integer bid) {
return bookMapper.deleteByPrimaryKey(bid);
}
public int insert(Book record) {
return bookMapper.insert(record);
}
public int insertSelective(Book record) {
return bookMapper.insertSelective(record);
}
public Book selectByPrimaryKey(Integer bid) {
return bookMapper.selectByPrimaryKey(bid);
}
public int updateByPrimaryKeySelective(Book record) {
return bookMapper.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(Book record) {
return bookMapper.updateByPrimaryKey(record);
}
@Override
public List<Book> selectBooksIn(List bookIds) {
return bookMapper.selectBooksIn(bookIds);
}
@Override
public List<Book> selectBooksIn1(String bname) {
return bookMapper.selectBooksIn1(bname);
}
@Override
public List<Book> selectBooksIn2(String bname) {
return bookMapper.selectBooksIn2(bname);
}
@Override
public List<Book> selectBooksIn3(String bname) {
return bookMapper.selectBooksIn3(bname);
}
@Override
public List<Book> list1() {
return bookMapper.list1();
}
@Override
public List<Book> list2() {
return bookMapper.list2();
}
@Override
public List<Book> list3(BookVo bookVo) {
return bookMapper.list3(bookVo);
}
@Override
public List<Map> list4(Map map) {
return bookMapper.list4(map);
}
@Override
public Map list5(Map map) {
return bookMapper.list5(map);
}
@Override
public List<Map> listPager(Map map, PageBean pageBean) {
if(pageBean != null && pageBean.isPagination()){
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
}
List<Map> maps = bookMapper.listPager(map);
if(pageBean != null && pageBean.isPagination()){
PageInfo pageInfo=new PageInfo(maps);
System.out.println("总记录数:"+pageInfo.getTotal());
System.out.println("当前页:"+pageInfo.getPageNum());
System.out.println("页大小:"+pageInfo.getPageSize());
pageBean.setTotal(pageInfo.getTotal()+"");
System.out.println("总页数:"+pageBean.getMaxPage());
}
return maps;
}
@Override
public List<Book> list6(BookVo bookVo) {
return bookMapper.list6(bookVo);
}
}