mybatis动态SQL以及分页模糊查询和返回结果集处理
- 1. mybatis动态sql
- ***BookMapper***
- ***BookMapper.xml***
- 2. 分页模糊查询和返回结果集处理
- ***Pom依赖***
- ***Mybatis.cfg.xml配置拦截器***
- ***BookService***
- ***BookServiceImpl***
- ***PageBean***
- ***StringUtils***
- ***BookVo***
- ***JUnit测试代码***
1. mybatis动态sql
BookMapper
List<Book> selectByIn(@Param("bookIds") List bookIds);
List<Book> selectBylike1(@Param("bname") String bname);
List<Book> selectBylike2(@Param("bname") String bname);
List<Book> selectBylike3(@Param("bname") String bname);
List<Book> list1();
List<Book> list2();
Book list3(BookVo bookVo);
List<Map> list4(Map map);
Map list5(Map map);
List<Map> list6(BookVo bookVo);
List<Map> list7(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.lin.mapper.BookMapper" >
<!--resultMap:适合使用返回值是自定义实体类的情况-->
<!--resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型-->
<!--下面会使用到这个BaseResultMap-->
<resultMap id="BaseResultMap" type="com.lin.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.lin.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.lin.model.Book" >
insert into t_mvc_book
<trim prefix="(" suffix=")" suffixOverrides="," >
<!-- trim:一样的sql语句拼接:prefix前缀,suffi 后缀。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.lin.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.lin.model.Book" >
update t_mvc_book
set bname = #{bname,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL}
where bid = #{bid,jdbcType=INTEGER}
</update>
<!--自己写的-->
<select id="selectByIn" resultType="com.lin.model.Book" parameterType="java.util.List">
select * from t_mvc_book where bid in
<!-- foreach 就是循环的意思,collection代表要被循环参数集合。
open和close代表开始和结束拼接字符串。separator代表item之间的分割符。
item就是当前正在循环的变量定义。就当java中的foreach看就能看懂了-->
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
<!--模糊查的三种方式-->
<!--注意:#{…}自带引号,${…}有sql注入的风险-->
<!--推荐使用这种-->
<select id="selectBylike1" resultType="com.lin.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like #{bname}
</select>
<!--此方式不会自动加 双引号,存在sql注入的风险-->
<select id="selectBylike2" resultType="com.lin.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like '${bname}'
</select>
<!--这种方式也能实现,不过比较麻烦,一般每谁去使用 -->
<select id="selectBylike3" resultType=com.lin.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.lin.model.Book">
select * from t_mvc_book
</select>
<select id="list3" resultType="com.lin.model.Book" parameterType="com.lin.model.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" parameterMap="java.util.Map">
select * from t_mvc_book
<where>
<!--如果 test 不为空,就进行if体的拼接-->
<if test="null != bname and bname!=''" >
and bname like #{bname} <! -- 这就是if体 -->
</if>
</where>
</select>
<select id="list5" resultType="java.util.Map" parameterMap="java.util.Map">
select * from t_mvc_book
<where>
<!--如果 test 不为空,就进行if体的拼接-->
<if test="null != bid and bid!=''" >
and bid = #{bid}<! -- 这就是if体 -->
</if>
</where>
</select>
<select id="list6" resultType="java.util.Map" parameterType="com.lin.model.BookVo">
select * from t_mvc_book
<where>
<if test="null != min and min != ''">
<![CDATA[ and #{min} < price ]]>
</if>
<if test="null != max and max != ''">
<![CDATA[ and #{max} > price ]]>
</if>
</where>
</select>
<select id="list7" resultType="java.util.Map" parameterType="com.lin.model.BookVo">
select * from t_mvc_book
<where>
<if test="null != min and min != ''">
and #{min} < price
</if>
<if test="null != max and max != ''">
and #{max} > price
</if>
</where>
</select>
</mapper>
2. 分页模糊查询和返回结果集处理
Pom依赖
- 动态sql、结果集处理和特殊字符处理上面注释写的都很清楚了,后面主要提一下分页的插件
- 导入分页插件pom
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
Mybatis.cfg.xml配置拦截器
- 将pagehelper插件配置到mybatis中,注意要配在运行环境之前
<plugins>
<!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
BookService
package com.lin.service;
import com.lin.model.Book;
import com.lin.model.BookVo;
import com.lin.util.PageBean;
import java.util.List;
import java.util.Map;
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> selectByIn( List bookIds);
List<Book> selectBylike1(String bname);
List<Book> selectBylike2(String bname);
List<Book> selectBylike3(String bname);
List<Book> list1();
List<Book> list2();
Book list3(BookVo bookVo);
List<Map> list4(Map map);
Map list5(Map book);
List<Map> listPager(Map map, PageBean pageBean);
List<Map> list6(BookVo bookVo);
List<Map> list7(BookVo bookVo);
}
BookServiceImpl
package com.lin.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lin.mapper.BookMapper;
import com.lin.model.Book;
import com.lin.model.BookVo;
import com.lin.service.BookService;
import com.lin.util.PageBean;
import java.util.List;
import java.util.Map;
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.updateByPrimaryKey(record);
}
@Override
public List<Book> selectByIn(List bookIds) {
return bookMapper.selectByIn(bookIds);
}
@Override
public List<Book> selectBylike1(String bname) {
return bookMapper.selectBylike1(bname);
}
@Override
public List<Book> selectBylike2(String bname) {
return bookMapper.selectBylike2(bname);
}
@Override
public List<Book> selectBylike3(String bname) {
return bookMapper.selectBylike3(bname);
}
@Override
public List<Book> list1() {
return bookMapper.list1();
}
@Override
public List<Book> list2() {
return bookMapper.list2();
}
@Override
public Book list3(BookVo bookVo) {
return bookMapper.list3(bookVo);
}
@Override
public List<Map> list4(Map map) {
return bookMapper.list4(map);
}
@Override
public Map list5(Map book) {
return bookMapper.list5(book);
}
@Override
public List<Map> listPager(Map map, PageBean pageBean) {
if(pageBean != null && pageBean.isPagination()){
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
}
List<Map> list = this.bookMapper.list4(map);
if(pageBean != null && pageBean.isPagination()){
PageInfo pageInfo=new PageInfo(list);
System.out.println("当前的页码:"+pageInfo.getPageNum());
System.out.println("页数据量:"+pageInfo.getSize());
System.out.println("总记录数:"+pageInfo.getTotal());
pageBean.setTotal(pageInfo.getTotal()+"");
}
return list;
}
@Override
public List<Map> list6(BookVo bookVo) {
return bookMapper.list6(bookVo);
}
@Override
public List<Map> list7(BookVo bookVo) {
return bookMapper.list7(bookVo);
}
}
PageBean
package com.lin.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);
}
public int getStartIndex() {
return (this.getPage()-1)*this.rows;
}
public int getMaxPage() {
int totalpage=this.total/this.rows;
if(this.total%this.rows!=0)
totalpage++;
return totalpage;
}
public int getNextPage() {
int nextPage=this.page+1;
if(this.page>=this.getMaxPage())
nextPage=this.getMaxPage();
return nextPage;
}
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
+ "]";
}
}
StringUtils
package com.lin.util;
public class StringUtils {
public static String toLikeStr(String str){
return "%"+str+"%";
}
}
BookVo
- vo类,就是value Object,用来处理查询条件所需要用到的而又不是数据库字段的属性
- 用来存放包括数据库表映射字段以及多余查询条件所用到的属性
package com.lin.model;
import java.util.List;
public class BookVo {
private List<String> bookIds;
private float min;
private float max;
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<String> getBookIds() {
return bookIds;
}
public void setBookIds(List<String> bookIds) {
this.bookIds = bookIds;
}
}
JUnit测试代码
package com.lin.test;
import com.lin.mapper.BookMapper;
import com.lin.model.Book;
import com.lin.model.BookVo;
import com.lin.service.BookService;
import com.lin.service.impl.BookServiceImpl;
import com.lin.util.PageBean;
import com.lin.util.SessionUtil;
import com.lin.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;
public class MapperSqlTest {
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 selectByIn() {
List list=new ArrayList();
list.add(2);
list.add(5);
list.add(27);
list.add(19);
List<Book> books = this.bookService.selectByIn(list);
for (Book book : books) {
System.out.println(book);
}
}
@Test
public void selectBylike() {
List<Book> books = this.bookService.selectBylike3("圣墟");
for (Book book : books) {
System.out.println(book);
}
}
@Test
public void list() {
Map map=new HashMap<>();
map.put("bid",27);
Map m = this.bookService.list5(map);
System.out.println(m);
}
@Test
public void listPage(){
Map map=new HashMap();
map.put("bname", StringUtils.toLikeStr("圣墟"));
PageBean pageBean=new PageBean();
List<Map> list = this.bookService.listPager(map, pageBean);
for (Map m : list) {
System.out.println(m);
}
}
@Test
public void sqlSpecial(){
BookVo bookVo=new BookVo();
bookVo.setMax(30);
bookVo.setMin(20);
List<Map> list = this.bookService.list7(bookVo);
for (Map m : list) {
System.out.println(m);
}
}
}