[mybastis动态sql和分页]
mybatis动态sql
If、trim、foreach
If :如果 name 不为空,就进行if体的拼接
<if test="bname != null" >
#{bname,jdbcType=VARCHAR},
</if>
trim:一样的sql语句拼接:prefix前缀,suffi 后缀。suffixOverrides 后缀覆盖
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="pwd != null" >
pwd,
</if>
</trim>
在映射文件中生成相关配置
foreach: 标签 遍历集合,批量查询、通常用于in关键字
<select id="selectByid" resultType="com.huangting.model.Book" parameterType="java.util.List">
select * from t_mvc_book where bid in
<foreach collection="bookId" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
测试
@Test
public void selectByid() {
List list =new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
List<Book> list1 = this.bookService.selectByid(list);
for (Book book : list1) {
System.out.println(book);
}
}
模糊查询
在BookMapper中设置方法
List<Book> selectBylike1(@Param("bname") String bookIds );
List<Book> selectBylike2(@Param("bname") String bookIds );
List<Book> selectBylike3(@Param("bname") String bookIds );
BookMapper.xml
注意:#{…}自带引号,${…}有sql注入的风险
参数中直接加入%%
<select id="selectBylike1" resultType="com.chen.model.Book">
select * from t_mvc_book where bname like #{bname}
</select>
<!-- 美元符号与井号符合传参的区别
美元符号需要手动打出单引号,而井号符号到数据库中是自动加上引号的
美元符号存在一定的安全隐患,对sql语句具有一定的不友好性
-->
<select id="selectBylike2" resultType="com.chen.model.Book">
select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectBylike3" resultType="com.chen.model.Book">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>
我们可以写一个工具类来给字符串加上百分号
package com.chen.util;
/**
* @author嘟嘟
*/
public class StringUtils {
public static String toLikeStr(String str){
return "%"+str+"%";
}
}
MapperSqlTest测试类
@Test
public void selectByLike() {
// List<Book> books = this.bookService.selectBylike1(StringUtils.toLikeStr("圣墟"));//①
// List<Book> books = this.bookService.selectBylike2("%圣墟 or bid !=1");//②
List<Book> books = this.bookService.selectBylike2("圣墟");//③
for (Book b : books){
System.out.println(b);
}
}
查询返回结果集的处理
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
BookMapper和BookServeice
// 1 使用resultMap返回自定义类型集合
List<Book> list1();
// 2 使用resultType返回List<T>
List<Book> list2();
// 3 使用resultType返回单个对象
Book list3(BookVo bookVo);
// 4 使用resultType返回List<Map>,适用于多表查询返回结果集
List<Map> list4(Map map);
// 5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
Map list5(Map map);
BookMapper.xml映射文件
<select id="list1" resultType="com.chen.model.Book">
select * from t_mvc_book
</select>
<select id="list2" resultType="com.chen.model.Book">
select * from t_mvc_book
</select>
<select id="list3" resultType="com.chen.model.Book" parameterType="com.chen.model.BookVo">
select * from t_mvc_book where bid in
<foreach collection="bookId" 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>
<if test="null != bname and bname !=''">
and bname like #{bname}
</if>
</where>
</select>
<select id="list5" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book
<where>
<if test="null != bid and bid !=''">
and bid = #{bid}
</if>
</where>
</select>
MapperSqlTest测试:
@Test
public void list() {
// 返回一个resultMap但是使用list<T>接收
// List<Book> books = this.bookService.list1();
// 返回的是resulttype使用list<T>接收
// List<Book> books = this.bookService.list2();
// 返回的是resulttype使用list<T>接收
// for (Book b : books){
// System.out.println(b);
// }
// 返回的是resulttype使用T接收
// BookVo bookVo =new BookVo();
// List list = new ArrayList();
// list.add(2);
// bookVo.setBookIds(list);
// Book book = this.bookService.list3(bookVo);
// System.out.println(book);
// 返回的是resulttype使用list<Map>接收
Map map =new HashMap();
// map.put("bname",StringUtil.toLikeStr("圣墟"));
// List<Map> list = this.bookService.list4(map);
// for (Map m : list) {
// System.out.println(m);
// }
// 返回的是resulttype使用Map接收
map.put("bid",2);
Map m = this.bookService.list5(map);
System.out.println(m);
}
mybatis的分页运用
导入pom依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
Mybatis.cfg.xml配置拦截器
<plugins>
<!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
使用PageHelper进行分页
导入分页工具类
PageBean.java
package com.chen.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
+ "]";
}
}
实现分页方法:
BookServiceImpl.java
@Override
public List<Map> ListPage(Map map, PageBean pageBean) {
//如果分页对象不为空就继续分页操作
if(pageBean != null && pageBean.isPagination()){
PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
}
List<Map> maps = this.bookMapper.list4(map);
//如果分页对象不为空,就输出分页后的结果信息
if(pageBean != null && pageBean.isPagination()){
PageInfo pageInfo = new PageInfo(maps);
System.out.println("当前页码:"+pageInfo.getPageNum());
System.out.println("一页大小:" + pageInfo.getPageSize());
System.out.println("符合条件记录数:"+pageInfo.getTotal());
}
return maps;
}
测试:
@Test
public void ListPager() {
Map map = new HashMap();
map.put("bname", StringUtils.toLikeStr("圣墟"));
PageBean pageBean = new PageBean();
List<Map> maps = this.bookService.ListPage(map, pageBean);
for (Map m : maps) {
System.out.println(m);
}
}
mybatis的特殊符号
>(>) <(<) &(&) 空格( ) <![CDATA[ <= ]]>
BookMapper设置方法:
//特殊字符处理
List<Map> list6(BookVo bookVo);
List<Map> list7(BookVo bookVo);
映射BookMapper.xml文件
<select id="list6" resultType="java.util.Map" parameterType="com.chen.model.BookVo">
select * from t_mvc_book
<where>
<if test="null != min and min != ''">
and price > #{min}
</if>
<if test="null != max and max != ''">
and price < #{max}
</if>
</where>
</select>
<select id="list7" resultType="java.util.Map" parameterType="com.chen.model.BookVo">
select * from t_mvc_book
<where>
<if test="null != min and min !=''">
<![CDATA[ and price > #{min} ]]>
</if>
<if test="null != max and max !=''">
<![CDATA[ and price < #{max} ]]>
</if>
</where>
</select>
测试:
@Test
public void listSpecoal() {
BookVo bookVo =new BookVo();
bookVo.setMin(80.0);
bookVo.setMax(300.0);
List<Map> list = this.bookService.list6(bookVo);
// List<Map> list = this.bookService.list7(bookVo);
for (Map map : list) {
System.out.println(map);
}
}