mybatis动态sql和分页
mybatis动态sql
1, trim :去空格
2,foreach
遍历集合,批量查询、通常用于in关键字
注意:使用foreach需要在接口里添加@Parma注解不然会报错
在BookMapper.xml添加对应的事务
<!--foreach标签使用-->
<select id="selectBooksIn" resultType="com.liuchunming.model.Book"
parameterType="java.util.List" >
select * from t_mvc_book where bid in
<foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
#{bid}
</foreach>
</select>
resultType:返回的类型
parameterType:参数的类型
collection:数据源
item:数据源赋予的变量
open:打开
close:关闭
separator:分隔符
测试:
模糊查询
模糊查询三种方式
#{…}
#将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。简单来说就是直接在参数中添加%%
${…}
$将传入的数据直接显示生成在sql中,不建议使用。因为这个方式是需要手动添加单引号的,如果传入有单引号的参数会照成sql注入风险
Concat
sql字符串中拼接%%
在接口中定义出三种方法
/**
* mybatis对模糊查询有三种方式:
* #{}
* ${}
* concat
* @param bname
* @return
*/
List<Book> selectBookLike1(@Param("bname") String bname);
List<Book> selectBookLike2(@Param("bname") String bname);
List<Book> selectBookLike3(@Param("bname") String bname);
创建事务
<select id="selectBookLike1" resultType="com.liuchunming.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like #{bname}
</select>
<select id="selectBookLike2" resultType="com.liuchunming.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectBookLike3" resultType="com.liuchunming.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>
测试
查询返回结果集的处理
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
1 使用resultMap返回自定义类型集合
2 使用resultType返回List
3 使用resultType返回单个对象
4 使用resultType返回List
5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
在接口中定义方法
创建事务
测试
@Test
public void list(){
//第一种方式
// List<Book> books = this.bookService.list1();
//第二种方式
// List<Book> books = this.bookService.list2();
List list =new ArrayList();
list.add(1);
list.add(12);
list.add(16);
// BookVo bookVo =new BookVo();
// bookVo.setBookIds(list);
//第三种方式
// List<Book> books = this.bookService.list3(bookVo);
// for (Book b : books) {
// System.out.println(b);
// }
Map map =new HashMap();
// map.put("bookIds",list);
//第四种方式
// List<Map> maplist = this.bookService.list4(map);
// for (Map m : maplist) {
// System.out.println(m);
// }
map.put("bid",1);
//第五种方式
System.out.println(this.bookService.list5(map));
}
分页
为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的
1,加入pom依赖
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>
注意:拦截器需要配置到environments运行环境上方
使用分页插件
Mapper层
Service层
测试
特殊字符处理
简单来说就是在BookMaapper.xml中是不能写大于小于号的所有只能用以下来转义
>(>)
<(<)
&(&)
空格( )
用一以下这种方式可以在中括号里面写任意字符
<![CDATA[ <= ]]>
测试
全部代码
项目结构:
是基于上一篇博客项目环境续写的
链接:mybatis入门(简单增删改).
BookMapper接口
package com.liuchunming.mapper;
import com.liuchunming.model.Book;
import com.liuchunming.model.vo.BookVo;
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
* 如果形参要在maooer.xml中使用就需要加上面注解
* @param bookIds
* @return
*/
List<Book> selectBooksIn(@Param("bookIds") List bookIds);
/**
* mybatis对模糊查询有三种方式:
* #{}
* ${}
* concat
* @param bname
* @return
*/
List<Book> selectBookLike1(@Param("bname") String bname);
List<Book> selectBookLike2(@Param("bname") String bname);
List<Book> selectBookLike3(@Param("bname") String bname);
/**
* mybatis结果集处理的五种情况
* @return
*/
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特殊字符的处理
* @param bookVo
* @return
*/
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.liuchunming.mapper.BookMapper" >
<resultMap id="BaseResultMap" type="com.liuchunming.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.liuchunming.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.liuchunming.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.liuchunming.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.liuchunming.model.Book" >
update t_mvc_book
set bname = #{bname,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL}
where bid = #{bid,jdbcType=INTEGER}
</update>
<!--foreach标签使用-->
<select id="selectBooksIn" resultType="com.liuchunming.model.Book"
parameterType="java.util.List" >
select * from t_mvc_book where bid in
<foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
#{bid}
</foreach>
</select>
<select id="selectBookLike1" resultType="com.liuchunming.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like #{bname}
</select>
<select id="selectBookLike2" resultType="com.liuchunming.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectBookLike3" resultType="com.liuchunming.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.liuchunming.model.Book">
select * from t_mvc_book
</select>
<select id="list3" resultType="com.liuchunming.model.Book" parameterType="com.liuchunming.model.vo.BookVo">
select * from t_mvc_book where bid in
<foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
#{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" item="bid" open="(" close=")" separator=",">
#{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 #{bname}
</select>
<select id="list6" resultType="com.liuchunming.model.Book" parameterType="com.liuchunming.model.vo.BookVo">
select * from t_mvc_book where <![CDATA[ price > #{min} and price < #{max} ]]>
</select>
</mapper>
BookService
package com.liuchunming.service;
import com.liuchunming.model.Book;
import com.liuchunming.model.vo.BookVo;
import com.liuchunming.util.PageBean;
import java.util.List;
import java.util.Map;
/**
* @authorliuchunming
* @site www.liuchunming.com
* @company xxx公司
* @create 2020-10-13 11:28
*/
public interface BookService {
int deleteByPrimaryKey(Integer bid);
int insert(Book record);
int insertSelective(Book record);
Book selectByPrimaryKey(Integer bid);
int updateByPrimaryKeySelective(Book record);
int updateByPrimaryKey(Book record);
List<Book> selectBooksIn(List bookIds);
List<Book> selectBookLike1( String bname);
List<Book> selectBookLike2( String bname);
List<Book> selectBookLike3( String bname);
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, PageBean pageBean);
List<Book> list6(BookVo bookVo);
}
BookServiceImpl
package com.liuchunming.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liuchunming.mapper.BookMapper;
import com.liuchunming.model.Book;
import com.liuchunming.model.vo.BookVo;
import com.liuchunming.service.BookService;
import com.liuchunming.util.PageBean;
import java.util.List;
import java.util.Map;
/**
* @authorliuchunming
* @site www.liuchunming.com
* @company xxx公司
* @create 2020-10-13 11:29
*/
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public BookMapper getBookMapper() {
return bookMapper;
}
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int deleteByPrimaryKey(Integer bid) {
return bookMapper.deleteByPrimaryKey(bid);
}
@Override
public int insert(Book record) {
return bookMapper.insert(record);
}
@Override
public int insertSelective(Book record) {
return bookMapper.insertSelective(record);
}
@Override
public Book selectByPrimaryKey(Integer bid) {
return bookMapper.selectByPrimaryKey(bid);
}
@Override
public int updateByPrimaryKeySelective(Book record) { return bookMapper.updateByPrimaryKeySelective(record); }
@Override
public int updateByPrimaryKey(Book record) {
return bookMapper.updateByPrimaryKeySelective(record);
}
@Override
public List<Book> selectBooksIn(List bookIds) {
return bookMapper.selectBooksIn(bookIds);
}
@Override
public List<Book> selectBookLike1(String bname) {
return bookMapper.selectBookLike1(bname);
}
@Override
public List<Book> selectBookLike2(String bname) {
return bookMapper.selectBookLike2(bname);
}
@Override
public List<Book> selectBookLike3(String bname) {
return bookMapper.selectBookLike3(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> list = bookMapper.listPager(map);
if(pageBean !=null && pageBean.isPagination()){
PageInfo pageInfo=new PageInfo(list);
System.out.println("总记录数:"+pageInfo.getTotal());
System.out.println("当前页" + pageInfo.getPageNum());
System.out.println("页大小" + pageInfo.getPageSize());
pageBean.setTotal(pageBean.getTotal()+"");
System.out.println("总页数:"+pageBean.getMaxPage());
}
return list;
}
@Override
public List<Book> list6(BookVo bookVo) {
return bookMapper.list6(bookVo);
}
}
BookVo
这个类主要作用是需要用到的某个字段但数据库没有
package com.liuchunming.model.vo;
import com.liuchunming.model.Book;
import java.util.List;
/**
* @author liuchunming
* @site www.liuchunming.com
* @company xxx公司
* @create 2020-10-14 10:58
*
*
* vo介绍
* mybatis、hibernate都是orm框架,表所存种子的列段在实体类model都有映射
* 实际开发中,会因为某些需求改变model,破坏model封装性
* 此时为了保证model的封装性,就可以使用vo类来完成指定的需求
*/
public class BookVo extends Book {
private Float min;
private Float max;
private List<Integer> bookIds;
public Float getMin() {
return min;
}
public void setMin(Float min) {
this.min = min;
}
public Float getMax() {
return max;
}
public void setMax(Float max) {
this.max = max;
}
public List<Integer> getBookIds() {
return bookIds;
}
public void setBookIds(List<Integer> bookIds) {
this.bookIds = bookIds;
}
}
PageBean
package com.liuchunming.util;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
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
+ "]";
}
}
SessionUtil
package com.liuchunming.util;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @authorliuchunming
* @site www.javaxl.com
* @company xxx公司
* @create 2018-12-10 21:59
*/
public class SessionUtil {
private static SqlSessionFactory sessionFactory;
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
static {
sessionFactory = new SqlSessionFactoryBuilder().build(SessionUtil.class.getResourceAsStream("/mybatis.cfg.xml"));
}
public static SqlSession openSession() {
SqlSession session = threadLocal.get();
if (null == session) {
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void main(String[] args) {
SqlSession session = openSession();
System.out.println(session.getConnection());
session.close();
// System.out.println(session.getConnection());
}
}
StringUtils
package com.liuchunming.util;
/**
* @author liuchunming
* @site www.liuchunming.com
* @company xxx公司
* @create 2020-10-13 22:47
*/
public class StringUtils {
public static String toLikeStr(String str){
return "%"+str+"%";
}
}
BookServiceTest 测试代码
package com.liuchunming.service;
import com.liuchunming.mapper.BookMapper;
import com.liuchunming.model.Book;
import com.liuchunming.model.vo.BookVo;
import com.liuchunming.service.impl.BookServiceImpl;
import com.liuchunming.util.PageBean;
import com.liuchunming.util.SessionUtil;
import com.liuchunming.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;
/**
* @authorliuchunming
* @site www.liuchunming.com
* @company xxx公司
* @create 2020-10-13 14:47
*/
public class BookServiceTest {
private BookService bookService;
SqlSession sqlSession;
@Before
public void setUp(){
BookServiceImpl bookService=new BookServiceImpl();
sqlSession = SessionUtil.openSession();
BookMapper mapper = sqlSession.getMapper(BookMapper.class);
bookService.setBookMapper(mapper);
this.bookService=bookService;
}
@Test
public void insert() {
Book book =new Book();
book.setBid(2);
book.setBname("mybatis增加2");
book.setPrice(24f);
bookService.insert(book);
}
@Test
public void selectByPrimaryKey() {
// Book book = this.bookService.selectByPrimaryKey(27);
this.bookService.deleteByPrimaryKey(27);
// System.out.println(book);
}
@After
public void tearDown() throws Exception{
sqlSession.commit();
sqlSession.close();
}
@Test
public void selectBooksIn() {
List list=new ArrayList();
list.add(1);
list.add(12);
list.add(16);
List<Book> books = this.bookService.selectBooksIn(list);
for (Book b : books) {
System.out.println(b);
}
}
/**
* #与$的区别
* $会引起sql攻击
* 因为需要人为加'号。如果传了个带'号的值会造成引号抵消
* select * from t_mvc_book where bname like '${bname}'
*
*
*/
@Test
public void selectBookLike() {
String bname = "my";
//第一种
// List<Book> books =this.bookService.selectBookLike1(StringUtils.toLikeStr(bname));
//第二种
List<Book> books =this.bookService.selectBookLike2(StringUtils.toLikeStr(bname));
//第三种
// List<Book> books =this.bookService.selectBookLike3(bname);
for (Book b : books) {
System.out.println(b);
}
}
@Test
public void list(){
//第一种方式
// List<Book> books = this.bookService.list1();
//第二种方式
// List<Book> books = this.bookService.list2();
List list =new ArrayList();
list.add(1);
list.add(12);
list.add(16);
// BookVo bookVo =new BookVo();
// bookVo.setBookIds(list);
//第三种方式
// List<Book> books = this.bookService.list3(bookVo);
// for (Book b : books) {
// System.out.println(b);
// }
Map map =new HashMap();
// map.put("bookIds",list);
//第四种方式
// List<Map> maplist = this.bookService.list4(map);
// for (Map m : maplist) {
// System.out.println(m);
// }
map.put("bid",1);
//第五种方式
System.out.println(this.bookService.list5(map));
}
@Test
public void listPager(){
Map map =new HashMap();
map.put("bname","%圣墟%");
PageBean pageBean=new PageBean();
List<Map> list = this.bookService.listPager(map, pageBean);
for (Map m : list) {
System.out.println(m);
}
}
@Test
public void list6(){
BookVo bookVo =new BookVo();
bookVo.setMax(25f);
bookVo.setMin(15f);
List<Book> books = this.bookService.list6(bookVo);
for (Book book : books) {
System.out.println(book);
}
}
}