目录
一、mybais的for循环
foreach循环
@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));
}
<?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.zking.oa.mapper.BookMapper"> <resultMap id="BaseResultMap" type="com.zking.model.Book"> <constructor> <idArg column="bid" javaType="java.lang.Integer" jdbcType="INTEGER" /> <arg column="bname" javaType="java.lang.String" jdbcType="VARCHAR" /> <arg column="price" javaType="java.lang.Float" jdbcType="REAL" /> </constructor> </resultMap> <sql id="Base_Column_List"> bid, bname, price </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_mvc_book where bid = #{bid,jdbcType=INTEGER} </select> <select id="selectByIn" parameterType="java.util.List" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_mvc_book where bid in <foreach collection="bookIds" open="(" close=")" separator="," item="bid"> #{bid} </foreach> </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from t_mvc_book where bid = #{bid,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.zking.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.zking.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.zking.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.zking.model.Book"> update t_mvc_book set bname = #{bname,jdbcType=VARCHAR}, price = #{price,jdbcType=REAL} where bid = #{bid,jdbcType=INTEGER} </update> <resultMap id="BaseResultMap" type="com.zking.model.Book"> <constructor> <idArg column="bid" javaType="java.lang.Integer" jdbcType="INTEGER" /> <arg column="bname" javaType="java.lang.String" jdbcType="VARCHAR" /> <arg column="price" javaType="java.lang.Float" jdbcType="REAL" /> </constructor> </resultMap> <sql id="Base_Column_List"> bid, bname, price </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> 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.zking.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.zking.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.zking.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.zking.model.Book"> update t_mvc_book set bname = #{bname,jdbcType=VARCHAR}, price = #{price,jdbcType=REAL} where bid = #{bid,jdbcType=INTEGER} </update> </mapper>
package com.zking.biz; import com.zking.model.Book; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author 锦鲤 * @site www.lucy.com * @company xxx公司 * @create 2022-08-10 17:14 */ public interface BookBiz { int deleteByPrimaryKey(Integer bid); Book selectByPrimaryKey(Integer bid); 模糊查询 通过in 查询,如果说参数是非实体类(book)那么急的加上注解@param 是collection属性的 // public List<Book> selectByIn( List bookIds) ; }
package com.zking.biz; import com.zking.model.Book; import com.zking.oa.mapper.BookMapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author 锦鲤 * @site www.lucy.com * @company xxx公司 * @create 2022-08-10 21:51 */ public class BookBizImpl implements BookBiz { 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(44); } @Override public Book selectByPrimaryKey(Integer bid) { return bookmapper.selectByPrimaryKey(44); } @Override public List<Book> selectByIn(List bookIds) { return bookmapper.selectByIn(bookIds); } // }
package com.zking.biz; import com.zking.oa.mapper.BookMapper; import com.zking.util.SessionUtil; import org.apache.ibatis.session.SqlSession; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.sql.SQLOutput; import java.util.Arrays; import java.util.List; /** * @author 锦鲤 * @site www.lucy.com * @company xxx公司 * @create 2022-08-10 21:57 */ public class BookBizImplTest { private BookBiz bookbiz; private SqlSession sqlSession; @Before public void setUp() throws Exception { System.out.println("方法初始化"); BookBizImpl bookBizpl=new BookBizImpl(); //工具类获取session对象 sqlSession = SessionUtil.openSession(); //从session里获取mapper BookMapper mapper1= sqlSession.getMapper(BookMapper.class); bookBizpl.setBookmapper(mapper1); this.bookbiz=bookBizpl; } @After public void tearDown() throws Exception { System.out.println("方法测试结束"); } @Test public void deleteByPrimaryKey() { System.out.println(bookbiz.deleteByPrimaryKey(44)); // SqlSession.commit();//提交事务 // SqlSession.close();//关闭 } @Test public void selectByPrimaryKey() { System.out.println("测试的业务方法"); System.out.println(bookbiz.selectByPrimaryKey(44)); } @Test public void test3() { int[] ints={1,2,3,4}; StringBuffer sb=new StringBuffer(); for (int i:ints){ sb.append(i).append(","); } System.out.println(sb.toString().substring(1)); } @Test public void getBookmapper() { } @Test public void setBookmapper() { } @Test public void selectByIn() { List<Integer> bookids=Arrays.asList(new Integer[]{31,32,33,34}); bookbiz.selectByIn(bookids).forEach(System.out::println); } }
二、模糊查询
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>
实现类
@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);
}
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都可以使用。
1 使用resultMap返回自定义类型集合
2 使用resultType返回List<T>
3 使用resultType返回单个对象
4 使用resultType返回List<Map>,适用于多表查询返回结果集
5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
四、第三方插件集成myabtis的应用
1、导入pom依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
2Mybatis.cfg.xml配置拦截器
<plugins>
<!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
3、使用PageHelper进行分页
4、处理分页结果
导入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
+ "]";
}
}
五、特殊字符处理
<select id="list6" resultType="com.javaxl.model.Book" parameterType="com.javaxl.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="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>