目录
- <update id="updateByPrimaryKeySelective" parameterType="com.javaxl.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>
之前自定义mvc的时代:
修改的SQL语句:
update t_oa_meeting_info set id=?,title=?,content=?,zhuchiren=?,author=?,..... where id=?
弊端:
会议编辑界面 infoEdit.jsp
意味着后台meetingInfo实体类 只有title、content属性值不为空,其他为空
进一步的:
update t_oa_meeting_info set id=?,title=纳新,content=招点学妹,zhuchiren=null,author=null,..... where id=?
update t_oa_meeting_info
title= 纳新,
price = #{content,jdbcType=REAL},
where bid = #{bid,jdbcType=INTEGER}
所以只要把 if标签 的拼接条件放在配置文件里面去拼接即可。
比如:
- @Test
- public void test3() {
- int[] ints={1,2,3,4,5,6};
- // 将数据编程字符串 1,2,3,4,5,6
- StringBuffer sb=new StringBuffer();
- for (int i:ints){
- sb.append(",").append(i);
- }
- String s=sb.toString();
- System.out.println(s.substring(1));
- }
运行结果:

但是,

因此forEach标签就来了.
- <select id="selectByIn" resultMap="BaseResultMap" parameterType="java.util.List" >
- select
- <include refid="Base_Column_List" />
- from t_mvc_book
- where bid in
- <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
- #{bid}
- foreach>
- select>
- package com.zking.mapper;
-
- import com.javaxl.model.Book;
- import org.apache.ibatis.annotations.Param;
-
- import java.util.List;
-
- 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);
-
- // 通过in关键字进行查询,讲解foreach标签的使用
- // 如果说参数是非实体类(book,Order,....),那么记得加上注解 @param,bookIds是对应collection属性的
- List<Book> selectByIn(@Param("bookIds") List bookIds);
-
- }
- package com.zking.mapper.biz.impl;
-
- import com.javaxl.model.Book;
- import com.zking.mapper.BookMapper;
- import com.zking.mapper.biz.BookBiz;
-
- import java.util.List;
-
- /**
- * @author 杨总
- * @create 2022-08-10 23:07
- */
- public class BookBizImpl implements BookBiz {
- private BookMapper bookMapper;
-
- //alt+insert 快速提供set/get/toString/构造方法
- //alt+enter 快速构建实现类,填充代码的前半部分 Ctrl+1
- 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 Book selectByPrimaryKey(Integer bid) {
- return bookMapper.selectByPrimaryKey(bid);
- }
-
- @Override
- public List<Book> selectByIn(List bookIds) {
- return bookMapper.selectByIn(bookIds);
- }
- }
- package com.zking.mapper.biz;
-
- import com.javaxl.model.Book;
-
- import java.util.List;
-
- /**
- * @author 杨总
- * @create 2022-08-10 23:02
- */
- public interface BookBiz {
-
- int deleteByPrimaryKey(Integer bid);
-
-
- Book selectByPrimaryKey(Integer bid);
-
- List<Book> selectByIn(List bookIds);
-
-
- }
测试:
- package com.zking.mapper.biz.impl;
-
- import com.zking.mapper.BookMapper;
- import com.zking.mapper.util.SessionUtil;
- import org.apache.ibatis.session.SqlSession;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
-
- import java.util.Arrays;
- import java.util.List;
-
- /**
- * @author 杨总
- * @create 2022-08-10 23:21
- */
- public class BookBizImplTest {
- private BookBizImpl bookBiz;
- private SqlSession sqlSession;
-
- @Before
- public void setUp() throws Exception {
- System.out.println("初始化方法...");
- BookBizImpl bookBiz = new BookBizImpl();
- // 从工具类中获取session对象
- sqlSession = SessionUtil.openSession();
- // 从session对象中获取mapper对象
- BookMapper mapper = sqlSession.getMapper(BookMapper.class);
- bookBiz.setBookMapper(mapper);
- this.bookBiz = bookBiz;
-
- }
-
- @After
- public void tearDown() throws Exception {
- System.out.println("方法测试结束...");
- sqlSession.commit();
- sqlSession.close();
- }
-
- @Test
- public void deleteByPrimaryKey() {
- bookBiz.deleteByPrimaryKey(44);
- }
-
-
-
- @Test
- public void selectByPrimaryKey() {
- System.out.println("测试的业务方法...");
- // System.out.println(bookBiz.getBookMapper());
- System.out.println(bookBiz.selectByPrimaryKey(44));
-
-
- }
-
- @Test
- public void test3() {
- int[] ints={1,2,3,4,5,6};
- // 将数据编程字符串 1,2,3,4,5,6
- StringBuffer sb=new StringBuffer();
- for (int i:ints){
- sb.append(",").append(i);
- }
- String s=sb.toString();
- System.out.println(s.substring(1));
- }
-
-
- @Test
- public void selectByIn(){
- List<Integer> bookIds = Arrays.asList(new Integer[]{31, 32, 33, 34});
- bookBiz.selectByIn(bookIds).forEach(System.out::println);
- }
- }
运行结果:

如上图可见 值已经查询到了。
①#{}
②${} ——(不建议使用该方式,有SQL注入风险)
关键:#{...}与${...}区别?
参数类型为字符串,#会在前后加单引号['],$则直接插入值③concat()
BookMapper.xml:
- <select id="selectBooksLike1" resultType="com.zking.model.Book" parameterType="java.lang.String">
- select * from t_mvc_book where bname like #{bname}
- select>
- <select id="selectBooksLike2" resultType="com.zking.model.Book" parameterType="java.lang.String">
- select * from t_mvc_book where bname like '${bname}'
- select>
- <select id="selectBooksLike3" resultType="com.zking.model.Book" parameterType="java.lang.String">
- select * from t_mvc_book where bname like concat('%',#{bname},'%')
- select>
BookBizImpl:
- @Override
- public List<Book> selectBooksLike1(String bname) {
- return bookMapper.selectBooksLike1(bname);
- }
-
- @Override
- public List<Book> selectBooksLike2(String bname) {
- return bookMapper.selectBooksLike2(bname);
- }
-
- @Override
- public List<Book> selectBooksLike3(String bname) {
- return bookMapper.selectBooksLike3(bname);
- }
- }
BookMapper :
- package com.zking.mapper;
-
- import com.javaxl.model.Book;
- import org.apache.ibatis.annotations.Param;
-
- import java.util.List;
-
- 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);
-
- // 通过in关键字进行查询,讲解foreach标签的使用
- // 如果说参数是非实体类(book,Order,....),那么记得加上注解 @param,bookIds是对应collection属性的
- List<Book> selectByIn(@Param("bookIds") List bookIds);
-
- List<Book> selectBooksLike1(@Param("bname") String bname);
- List<Book> selectBooksLike2(@Param("bname") String bname);
- List<Book> selectBooksLike3(@Param("bname") String bname);
-
-
-
- }
测试:
- @Test
- public void selectBooksLike1(){
- bookBiz.selectBooksLike1("%圣墟%").forEach(System.out::println);
-
- }
运行结果:

BookMapper.xml:

再测试:
- @Test
- public void selectBooksLike2(){
- bookBiz.selectBooksLike2("%圣墟%").forEach(System.out::println);
- }
会报错:

更改回来,也就是加上引号:
- <select id="selectBooksLike2" resultType="com.zking.model.Book" parameterType="java.lang.String">
- select * from t_mvc_book where bname like '${bname}'
- select>
即正常:
(参数传递)

跟前面对比:
(占位符)

concat:
(无需加百分号)
- @Test
- public void selectBooksLike3(){
- bookBiz.selectBooksLike2("圣墟").forEach(System.out::println);
- }
运行结果:

——MyBatis中#和$的区别
1. # 将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by '111',
如果传入的值是id,则解析成的sql为order by "id".
2. $ 将传入的数据直接显示生成在sql中。
如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id,
如果传入的值是id,则解析成的sql为order by id.
3. # 方式能够很大程度防止sql注入。
4. $ 方式无法防止Sql注入。
5. $ 方式一般用于传入数据库对象,例如传入表名.。
6. 一般能用 # 的就别用 $ 。
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
如果是单表的情况下,resultType与resultMap都可以使用。
不管返回一条数据,还是多条数据,都应该用java.util.Map进行接收
如果是多条数据,那么返回值List
1 使用resultMap返回自定义类型集合
2 使用resultType返回List
3 使用resultType返回单个对象
4 使用resultType返回List
5 使用resultType返回Map
,适用于多表查询返回单个结果集
BookMapper.xml:
- <select id="list1" resultMap="BaseResultMap">
- select * from t_mvc_book
- select>
- <select id="list2" resultType="com.model.Book">
- select * from t_mvc_book
- select>
- <select id="list3" resultType="com.model.Book" parameterType="com.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>
BookMapper :
- package com.zking.mapper;
-
- import com.model.Book;
- import com.model.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);
-
- // 通过in关键字进行查询,讲解foreach标签的使用
- // 如果说参数是非实体类(book,Order,....),那么记得加上注解 @param,bookIds是对应collection属性的
- List<Book> selectByIn(@Param("bookIds") List bookIds);
-
- List<Book> selectBooksLike1(@Param("bname") String bname);
- List<Book> selectBooksLike2(@Param("bname") String bname);
- List<Book> selectBooksLike3(@Param("bname") String bname);
-
- // list1 list2的结论是对于单表查询而言,可以用它resultType/resultMap接收,但是多表必须用resultMap接收
- List<Book> list1();
- List<Book> list2();
- // 如果要传入多个查询参数,必须以对象的方式进行传递
- List<Book> list3(BookVo vo);
- // 如果是返回一条数据,那么返回值Map
- // 如果是多条数据,那么返回值List
- List<Map> list4();
- Map list5(Map map);
-
-
- }
BookBizImpl :
- package com.zking.mapper.biz.impl;
-
- import com.model.Book;
- import com.model.BookVo;
- import com.zking.mapper.BookMapper;
- import com.zking.mapper.biz.BookBiz;
-
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author 杨总
- * @create 2022-08-10 23:07
- */
- public class BookBizImpl implements BookBiz {
- private BookMapper bookMapper;
-
- //alt+insert 快速提供set/get/toString/构造方法
- //alt+enter 快速构建实现类,填充代码的前半部分 Ctrl+1
- 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 Book selectByPrimaryKey(Integer bid) {
- return bookMapper.selectByPrimaryKey(bid);
- }
-
- @Override
- public List<Book> selectByIn(List bookIds) {
- return bookMapper.selectByIn(bookIds);
- }
-
-
- @Override
- public List<Book> selectBooksLike1(String bname) {
- return bookMapper.selectBooksLike1(bname);
- }
-
- @Override
- public List<Book> selectBooksLike2(String bname) {
- return bookMapper.selectBooksLike2(bname);
- }
-
- @Override
- public List<Book> selectBooksLike3(String bname) {
- return bookMapper.selectBooksLike3(bname);
- }
-
- @Override
- public List<Book> list1() {
-
- return bookMapper.list1();
- }
-
-
-
- @Override
- public List<Book> list2() {
- return bookMapper.list2();
- }
-
- @Override
- public List<Book> list3(BookVo vo) {
- return bookMapper.list3(vo);
- }
-
- @Override
- public List<Map> list4() {
- return bookMapper.list4();
- }
-
- @Override
- public Map list5(Map map) {
- return bookMapper.list5(map);
- }
-
-
- }
BookBiz :
- package com.zking.mapper.biz;
-
- import com.model.Book;
- import com.model.BookVo;
-
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author 杨总
- * @create 2022-08-10 23:02
- *
- * ctrl+T 跳到接口的实现类
- */
- public interface BookBiz {
-
- public int deleteByPrimaryKey(Integer bid);
-
-
- public Book selectByPrimaryKey(Integer bid);
-
- List<Book> selectByIn(List bookIds);
-
- public List<Book> selectBooksLike1(String bname);
- public List<Book> selectBooksLike2(String bname);
- public List<Book> selectBooksLike3(String bname);
-
-
- List<Book> list1();
- List<Book> list2();
- List<Book> list3(BookVo vo);
- List<Map> list4();
- Map list5(Map map);
-
-
-
-
-
- }
测试list1、list2:
(
结论是对于单表查询而言,可以用它resultType/resultMap接收,但是多表必须用resultMap接收
)
- @Test
- public void list1() {
- bookBiz.list1().forEach(System.out::println);
- }
-
- @Test
- public void list2() {
- bookBiz.list2().forEach(System.out::println);
- }
运行结果分别如下:


测试 list3:
(
如果要传入多个查询参数,必须以对象的方式进行传递
)
- @Test
- public void list3() {
- BookVo vo=new BookVo();
- vo.setBookIds(Arrays.asList(new Integer[]{31,32,33,34}));
- bookBiz.list3(vo).forEach(System.out::println);
- }
运行结果如下:

测试 list4:
(
如果是返回一条数据,那么返回值Map
如果是多条数据,那么返回值List
)
- @Test
- public void list4() {
- bookBiz.list4().forEach(System.out::println);
- }
运行结果如下:

测试 list5:
- @Test
- public void list5() {
- Map map=new HashMap();
- map.put("bid",32);
- System.out.println(bookBiz.list5(map));
- }
运行结果如下:

Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的
使用分页插件步奏
1、导入pom依赖
<groupId>com.github.pagehelpergroupId> <artifactId>pagehelperartifactId> <version>5.1.2version>2、Mybatis.cfg.xml配置拦截器
<plugin interceptor="com.github.pagehelper.PageInterceptor"> plugin>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>
4、处理分页结果
BookVo :
- package com.model;
-
- import java.util.List;
-
- /**
- * @author 杨总
- * @create 2022-08-12 0:42
- */
- public class BookVo extends Book{
- private List bookIds;
- private int min;
- private int max;
-
- public int getMax() {
- return max;
- }
-
- public void setMax(int max) {
- this.max = max;
- }
-
- public int getMin() {
- return min;
- }
-
- public void setMin(int min) {
- this.min = min;
- }
-
- public List getBookIds() {
- return bookIds;
- }
-
- public void setBookIds(List bookIds) {
- this.bookIds = bookIds;
- }
-
-
-
-
-
- }
BookMapper:
- // 利用第三方插件进行分页
- List<Map> listPager(Map map);
BookBizImpl:
- @Override
- public List<Map> listPager(Map map, PageBean pageBean) {
- // pageHelper分页插件相关代码
- if(pageBean != null && pageBean.isPagination()){
- PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
- }
-
- List<Map> maps=bookMapper.listPager(map);
-
- if(pageBean != null && pageBean.isPagination()){
- // 处理查询结果的前提,是需要分页的
- PageInfo info=new PageInfo(maps);
- pageBean.setTotal(info.getTotal()+"");
- return info.getList();
- }
-
- return maps;
- }
BookBiz:
List<Map> listPager(Map map, PageBean pageBean);
PageBean :
- package com.zking.pagination.entity;
-
- 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
- + "]";
- }
- }
测试:
- @Test
- public void listPager(){
- Map map=new HashMap();
- map.put("bname","圣墟");
- // bookBiz.listPager(map).forEach(System.out::println);
- // 查询出第二页的20条数据
- PageBean pageBean=new PageBean();
- pageBean.setPage(2);
- pageBean.setRows(20);
- bookBiz.listPager(map,pageBean).forEach(System.out::println);
- }

struts拦截器
定义一个拦截器类
invoke
sysout("action方法被调用前执行的功能")
method.invoke
sysout("action方法被调用后执行的功能")
struts-sy.xml
将拦截器的类申明到interceptors
引用拦截器
>(>)
<(<)
&(&)
空格( )
(用其包裹会被转义成sql语句中的字符)
- select * from t_mvc_book
-
- <if test="null != min and min != ''">
-
- if>
- <if test="null != max and max != ''">
- price ]]>
- if>
-
-
- <select id="list7" resultType="com.javaxl.model.Book" parameterType="com.javaxl.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>
BookBizImpl:
- @Override
- public List<Book> list6(BookVo vo) {
- return bookMapper.list6(vo);
- }
-
- @Override
- public List<Book> list7(BookVo vo) {
- return bookMapper.list7(vo);
- }
测试:
- @Test
- public void list6(){
- BookVo vo=new BookVo();
- vo.setMax(45);
- vo.setMin(35);
- bookBiz.list6(vo).forEach(System.out::println);
- }
-
- @Test
- public void list7(){
- BookVo vo=new BookVo();
- vo.setMax(45);
- vo.setMin(35);
- bookBiz.list7(vo).forEach(System.out::println);
- }

