mybatis中resulthandler的用法
作者:杭川奇迹
这篇文章主要介绍了mybatis中resulthandler的用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
resulthandler的用法
ResultHandler,顾名思义,对返回的结果进行处理,最终得到自己想要的数据格式或类型。也就是说,可以自定义返回类型。下面通过一个例子讲解它的使用方法:
创建实体类
package com.ccb.demossm.entity; import com.ccb.demossm.annotation.MyAnnotation; import org.springframework.stereotype.Component; @Component public class Users { //用户ID private String userId; //用户名 private String userName; //用户密码 private String userPwd; //用户性别 public String sex; //备注 protected String mark; public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public Users() { } public Users(String userId) { this.userId = userId; } }
sql,返回值类型要写
<select id="getUserResult" resultType="com.ccb.demossm.entity.Users"> select u.userId,u.userName, u.userPwd from users u </select>
Mapper,返回值必须是void
void getUserResult(ResultHandler<Users> resultHandler);package com.ccb.demossm.mapper; import com.ccb.demossm.entity.Users; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; @Repository @SpringBootApplication public interface UsersMapper { void getUserResult(ResultHandler<Users> resultHandler); }
Test
package com.ccb.demossm; import com.ccb.demossm.entity.Users; import com.ccb.demossm.mapper.UsersMapper; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) public class TestResultHandle { @Autowired private UsersMapper usersMapper; @Test public void test() { usersMapper.getUserResult(new ResultHandler<Users>() { @Override public void handleResult(ResultContext<? extends Users> resultContext) { Users resultObject = resultContext.getResultObject(); String userId = resultObject.getUserId(); //写数据处理业务 System.out.println(userId); } }); } }
ResultHandler(传入map返回map)
测试代码
package com.xwhbshweb.service; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; public interface OrdersService { /** * 返回某日订单成交数及当日成交总金额 day 的格式为 2018/01/30 * * 若 day 为 null 则返回总成交订单及总成交金额 * * @param id * 商户号 * @param day * @return */ public Map<String, String> getOrderCountTotal(String id, String day); /** * 处理 select 结果 * * @author Administrator * */ class OrdersResultHandler implements ResultHandler { private final Map<String, String> mappedResults = new HashMap<String, String>(); @Override public void handleResult(ResultContext resultContext) { Map map = (Map) resultContext.getResultObject(); if (map.get("count") instanceof Long) { System.out.println("count Long "); if (null == String.valueOf((Long) map.get("count")) || String.valueOf((Long) map.get("count")).equals("")) { mappedResults.put("count", "0"); } else { mappedResults.put("count", String.valueOf((Long) map.get("count"))); } } if (map.get("total") instanceof Double) { System.out.println("total Long "); String total = String.valueOf((Double) map.get("total")).split("\\.")[0]; if (total.equals("0")) { mappedResults.put("total", "0"); }else { float yuan = Float.valueOf(total) / 1000; mappedResults.put("total", String.valueOf(yuan)); } } } public Map getMappedResults() { return mappedResults; } } }
实现
package com.xwhbshweb.service.imp; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.stereotype.Service; import com.xwhbshweb.config.MybatisSqlSessionFactory; import com.xwhbshweb.service.OrdersService; @Service public class OrdersServiceI implements OrdersService { private SqlSessionFactory sqlSessionFactory = MybatisSqlSessionFactory.getOne(); @Override public Map<String, String> getOrderCountTotal(String id,String day) { SqlSession session = sqlSessionFactory.openSession(true); Map<String, String> params = new HashMap<String, String>(); params.put("id", id); if (null == day) { params.put("day", "%"); }else { params.put("day", day+"%"); } OrdersService.OrdersResultHandler handler = new OrdersService.OrdersResultHandler(); session.select("com.xwhbank.cn.config.mybatis.namespace.ordersMapper.selectDayOrderCountTotal", params, handler); session.close(); Map<String,String> map =handler.getMappedResults(); return map; } }
xml
<?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.xwhbank.cn.config.mybatis.namespace.ordersMapper"> <select id="selectOne" resultType="orders"> select * from orders where the_super_id = #{id}; </select> <select id="selectDayOrderCountTotal" parameterType="java.util.Map" resultType="java.util.HashMap"> select count(*) as count,SUM(money_to_tenant) as total from orders where the_super_id = #{id} and order_time like #{day} and state='2'; </select> <insert id="insertOne" parameterType="orders"> insert into orders (id,tenant_order_no,the_super_id,state,money_amount,cut,money_to_tenant,money_to_xwh,pay_way,good_info,asy_notify_url,sy_return_url,sign_,order_time,sharding_id) values ("next value for MYCATSEQ_order",#{tenant_order_no},#{the_super_id},#{state},#{money_amount},#{cut},#{money_to_tenant},#{money_to_xwh},#{pay_way},#{good_info},#{asy_notify_url},#{sy_return_url},#{sign_},#{order_time},#{sharding_id}); </insert> </mapper>
注意传入 map参数 及 传出map参数 的颜色对应
map传入值时 若是不同类型 将 map的值改为Object就好了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。