1.mybatis动态sql
1.1 if
1.2 trim
1.3 foreach
遍历集合,批量查询、通常用于in关键字
1.4 其他
choose/set/where
BookMapper.java
List<Book> selectBooksIn(@Param("bookIds") List bookIds);
BookMapper.xml
<!--foreach标签-->
<select id="selectBooksIn" resultType="com.bk201.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>
BookService.java
List<Book> selectBooksIn(List bookIds);
然后实现
BookServiceImpl.java
public List<Book> selectBooksIn(List bookIds) {
return bookMapper.selectBooksIn(bookIds);
}
然后来测试一下
BookServletImplTest.java
@Test
public void selectBooksIn() {
List bookIds = new ArrayList();
bookIds.add(12);
bookIds.add(13);
bookIds.add(16);
for (Book book : this.bookService.selectBooksIn(bookIds)) {
System.out.println(book);
}
}
这个需要留意
2.模糊查询(3种方式)
1 参数中直接加入%%
2 使用${...}代替#{...}(不建议使用该方式,有SQL注入风险)
关键:#{...}与${...}区别?
参数类型为字符串,#会在前后加单引号['],$则直接插入值
注:
1) mybatis中使用OGNL表达式传递参数
2) 优先使用#{...}
3) ${...}方式存在SQL注入风险
3 SQL字符串拼接CONCAT
BookMapper.java
List<Book> selectBookLike1(@Param("bname") String banme);
List<Book> selectBookLike2(@Param("bname") String banme);
List<Book> selectBookLike3(@Param("bname") String banme);
BookMapper.xml
<!--模糊查询-->
<select id="selectBookLike1" resultType="com.bk201.model.Book" parameterType="java.lang.String">
select * from t_mvc_book
<where>
bname like #{bname}
</where>
</select>
<select id="selectBookLike2" resultType="com.bk201.model.Book" parameterType="java.lang.String">
select * from t_mvc_book
<where>
bname like '${bname}'
</where>
</select>
<select id="selectBookLike3" resultType="com.bk201.model.Book" parameterType="java.lang.String">
select * from t_mvc_book
<where>
bname like concat(concat('%',#{bname}),'%')
</where>
</select>
BookService.java
List<Book> selectBookLike1(String banme);
List<Book> selectBookLike2(String banme);
List<Book> selectBookLike3(String banme);
BookServiceImpl.java
@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);
}
1) mybatis中使用OGNL表达式传递参数
2) 优先使用#{...}
3) ${...}方式存在SQL注入风险
BookServletImplTest.java
@Test
public void selectBookLike() {
// for (Book book : this.bookService.selectBookLike1("%圣墟%")) {
// System.out.println(book);
// }
// for (Book book : this.bookService.selectBookLike2("%圣墟%")) {
// System.out.println(book);
// }
for (Book book : this.bookService.selectBookLike3("%圣墟%")) {
System.out.println(book);
}
}
3.查询返回结果集的处理
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
3.1 使用resultMap返回自定义类型集合
3.2 使用resultType返回List<T>
3.3 使用resultType返回单个对象
3.4 使用resultType返回List<Map>,适用于多表查询返回结果集
3.5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
BookVo.java
package com.bk201.model;
import java.util.List;
/**
* @author bk201
* @site www.fellingss.com
* @company
* @create 2019-11-18 14:47
* <p>
* vo类专门用来封装多表联查信息用于展示的
* 封装查询条件
*/
public class BookVo extends Book {
private List<Integer> bookIds;
public List<Integer> getBookIds() {
return bookIds;
}
public void setBookIds(List<Integer> bookIds) {
this.bookIds = bookIds;
}
}
BookMapper.java 和 BookServlet.java
List<Book> list1();
List<Book> list2();
List<Book> list3(BookVo bookVo);
List<Map> list4();
Map list5(Map map);
BookMapper.xml
<!--返回结果集的处理-->
<select id="list1" resultMap="BaseResultMap">
select * from t_mvc_book
</select>
<select id="list2" resultType="com.bk201.model.Book">
select * from t_mvc_book
</select>
<select id="list3" resultType="com.bk201.model.Book" parameterType="com.bk201.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">
select * from t_mvc_book
</select>
<select id="list5" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bid = #{bid}
</select>
BookServletImpl.java
@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() {
return bookMapper.list4();
}
@Override
public Map list5(Map map) {
return bookMapper.list5(map);
}
BoookServletImplTest.java
//查询返回结果集
@Test
public void list1() {
for (Book book : this.bookService.list1()) {
System.out.println(book);
}
}
@Test
public void list2() {
for (Book book : this.bookService.list2()) {
System.out.println(book);
}
}
@Test
public void list3() {
BookVo bookVo = new BookVo();
List bookIds = new ArrayList();
bookIds.add(12);
bookIds.add(13);
bookIds.add(16);
bookVo.setBookIds(bookIds);
for (Book book : this.bookService.list3(bookVo)) {
System.out.println(book);
}
}
@Test
public void list4() {
for (Map map : this.bookService.list4()) {
System.out.println(map);
}
}
@Test
public void list5() {
Map map = new HashMap();
map.put("bid",12);
Map book = this.bookService.list5(map);
System.out.println(book);
}
结果图:
4.分页查询
为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和 边界limit 取结果),在大数据量的情况下这样的分页基本上是没有用的
struts拦截器
定义一个拦截器类
invoke
sysout("action方法被调用前执行的功能")
method.invoke
sysout("action方法被调用后执行的功能")
struts-sy.xml
将拦截器的类申明到interceptors
引用拦截器
<action>
<interceptor-ref>
pom依赖
pom.xml
<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>
使用分页插件
PageBean.java
package com.bk201.utis;
/**
* @author bk201
* @site www.fellingss.com
* @company
* @create 2019-11-17 18:49
*/
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
// 保留上一次的请求地址
private String url;
// 保留上一次请求所携带的参数
private Map<String, String[]> paMap = new HashMap<>();
/**
* pageBean初始化
* @param req
*/
public void setRequest(HttpServletRequest req) {
//改变它第几页的数据
this.setPage(req.getParameter("page"));
//改变它每页展示的数据
this.setRows(req.getParameter("rows"));
//控制页面是否分页
this.setPagination(req.getParameter("pagination"));
this.setUrl(req.getRequestURL().toString());
this.setPaMap(req.getParameterMap());
}
public void setPagination(String parameter) {
// 当你填false就不分页
if("false".equals(pagination)) {
this.setPagination(false);
}
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.setRows(Integer.valueOf(rows));
}
}
public void setPage(String page) {
// 如果不为空的时候
if(StringUtils.isNotBlank(page)){
this.setPage(Integer.valueOf(page));
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getPaMap() {
return paMap;
}
public void setPaMap(Map<String, String[]> paMap) {
this.paMap = paMap;
}
private boolean pagination = true;// 是否分页
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = 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 pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
/**
* 最大页码
* @return
*/
public int getMaxPage() {
return this.total % this.rows == 0 ? this.total/this.rows : this.total/this.rows + 1;
}
/**
* 获取下一页
* @return
*/
public int getNextPage() {
return this.page < this.getMaxPage() ? this.page+1 : this.page;
}
/**
* 上一页
* @return
*/
public int getPreviousPage() {
return this.page > 1 ? this.page-1 : this.page;
}
}
StringUtils.java
package com.bk201.utis;
/**
* @author bk201
* @site www.fellingss.com
* @company
* @create 2019-11-17 18:50
*/
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
BookService.java
List<Map> listPager(Map map, PageBean pageBean);
BookMapper.java
List<Map> listPager(Map map);
BookMapper.xml
<!--分页查询-->
<select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book
<where>
<if test="bname != null and bname != ''">
bname like concat(concat('%',#{bname}),'%')
</if>
</where>
</select>
PageHelper进行分页
BookServiceImpl.java
@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(pageBean.getTotal() + "");
}
return list;
}
BookServiceImplTest.java
@Test
public void listPage() {
Map map = new HashMap();
map.put("bname","圣墟");
PageBean pageBean = new PageBean();
// pageBean.setPagination(false); //不分页
pageBean.setPage(5);
for (Map m : this.bookService.listPager(map, pageBean)) {
System.out.println(m);
}
}
5、特殊字符处理
>(>)
<(<)
&(&)
空格( )
<![CDATA[ <= ]]>
BookVo.java
package com.bk201.model;
import java.util.List;
/**
* @author bk201
* @site www.fellingss.com
* @company
* @create 2019-11-18 14:47
* <p>
* vo类专门用来封装多表联查信息用于展示的
* 封装查询条件
*/
public class BookVo extends Book {
private List<Integer> 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<Integer> getBookIds() {
return bookIds;
}
public void setBookIds(List<Integer> bookIds) {
this.bookIds = bookIds;
}
}
BookMapper.xml
<!--处理特殊字符-->
<select id="list6" resultType="com.bk201.model.Book" parameterType="com.db201.model.BookVo">
select * from t_mvc_book where <![CDATA[ price > #{min} and price < #{max} ]]>
</select>
BookMapper.java和 BookServlet.java
List<Book> list6(BookVo bookVo);
BookServiceImpl.java
@Override
public List<Book> list6(BookVo bookVo) {
return bookMapper.list6(bookVo);
}
测试
BookServiveImplTest.java
@Test
public void list6() {
BookVo bookVo = new BookVo();
bookVo.setMax(20f);
bookVo.setMin(15f);
for (Book book : this.bookService.list6(bookVo)) {
System.out.println(book);
}
}