mybatis常用操作

mybatis常用操作

背景

最近开发了一个管理平台,使用mybatis作为ORM框架,整理了常用的几种较复杂的操作

准备

准备一张表格
应用表:tb_business

   create table 'tb_business'{
    	'id' varchar(50) NOT NULL COMMENT '业务id',
    	'status' tinyint(2) NOT NULL COMMENT '业务状态,0:禁用,1:正常,2:删除 ,默认为1',
    	'desc' varchar(50) NOT NULL COMMENT '业务id',
    	PRIMARY KEY ('id')
    }

映射实体 Business

	@Data
   public class Business{
		private String id;
		private Integer status;
		private String desc;
	}

批量新增

mapper:
 int insertBatch(List<Business> businessList);

xml:
    <insert id = "insertBatch" parameterType = "java.util.List">
    	insert into tb_business (id , status , desc)
    	values
    	<foreach collections = "list" item = "item" index = "index" separator = ",">
    	(#{item.id} , #{item.status } , #{item.desc})
    	</foreach>
    </insert>

注意分隔符separator = “,”

批量更新

批量删除

根据多条件字段批量删除

 mapper:
 int deleteBatch(List<Business> businessList);
 
 xml:
<delete id = “deleteBatch” parameterType = "java.util.List">
	delete from tb_business  where
	<foreach collections = "list" item = "item" index = "index" separator = "or">
    	( #{item.status } 
			and
		#{item.desc})
    </foreach>
</delete >

注意分隔符separator = “or”

分页查找

封装一个分页结果对象

@Data
public class  PageResult<T> {
	private int pageNumber;	//当前页码
	private int pageSize;	//每页数据量
	private int totalPage;	//总页数
	private int totalRow;	//总数据条数
	private List<T> content;		//数据内容
}

业务代码

 //map封装查询条件
 Map<String,Object> criteriaMap = new HashMap<>();
 criteriaMap .put("startRow" , startRow - 1);		//注意mysql的分页查询需要减一
 criteriaMap .put("pageSize" , pageSize);
 criteriaMap .put("status" , status);
//查询总条数
int  totalRow = businessMapper.selectTotalRow(criteriaMap);
//查询总数据量
List<Business> businessList = businessMapper.selectPage(criteriaMap);
//设置分页结果
totalPage = (int)Math.ceil((float)totaalRow / size);
PageResult<Business>  businessPageResult = new PageResult<>();
businessPageResult .setPageNumber(startRow);
businessPageResult .setPageSize(pageSize)
businessPageResult .setTotalPage(totalPage )
businessPageResult .setTotalRow(totalRow )
businessPageResult .setContent(businessList )

xml

<select id = "selectTotalRow" parameter = "java.util.Map" resultType = "java.lang.Integer">
select count(1)
   from tb_business
  <where>
	<if test = "status !=null">
		status = #{status}
	</if>
  </where>
</select>

<select id = "selectPage" parameter = "java.util.Map"  resultType = "cn.xxx.Business">
select *
   from tb_business
  <where>
	<if test = "status !=null">
		status = #{status}
	</if>
  </where>
  limit #{startRow} , #{pageSize}
</select>

过滤查找

同分页查询使用map封装查询条件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值