mybatis用法总结

一.设置的resutType为Integer/Double类时

此时java接收的对象即可以是单个对象,也可以是List对象,具体如下:

//dao文件
List<Integer> selectNotTest();
Double selMaxRetracement(@Param(value = "account") Integer account);

//xml文件
<!--查询非test账号集合-->
<select id="selectNotTest" resultType="Integer">
    select distinct(account) from mt4list_rel
</select>
<!--查询账号得最大回撤值-->
<select id="selMaxRetracement" resultType="Double">
    select MaxRetracement from retracement_index where Account=#{account}
</select>

二.设置的resultType为hashmap时设置

此时mapper文件中设置的resultType为hashmap,java中具体接收的是Map,同时返回的数据中,key为select语句中设置的别名,value为计算的数值,比如:下面的语句中,map中的一个key-value会是如下:key--allOrderNum,value--count(*)计算出来的数值

//dao文件
Map<String,Object> selectAccountDeatail(@Param(value = "account")String table);

//xml文件
<!--查询账户的总订单数,总手数,平仓总盈亏,平均手数-->
<select id="selectAccountDeatail" resultType="hashmap">
    select count(*) as allOrderNum,sum(Volume) as allVolumes,sum(profit) as historyProfit,sum(Volume)/count(*) as avgVolume from ${account} where cmd in ('buy','sell')
</select>

三.返回实体类得时候封装成resultMap

resultType与resultMap只能存在一个,用resultMap将数据库的字段与实体类进行匹配,然后返回的一个List,同事List中的中的元素为数据库表对应的实体类,具体如下:

//dao文件
List<CloseOrder> queryCloseOrderByAccount(@Param(value = "list") String[] list);

//xml文件
<resultMap id="CloseOrderResultMap" type="com.kflh.boxApi.apiNoCheckWestffs.entity.CloseOrder">
    <id column="id" property="id"/>
    <result column="closeorder" property="closeOrder"/>
    <result column="account" property="account"/>
    <result column="symbol" property="symbol"/>
    <result column="cmd" property="cmd"/>
    <result column="Volume" property="volume"/>
    <result column="OpenTime" property="openTime"/>
    <result column="OpenPrice" property="openPrice"/>
    <result column="SL" property="sl"/>
    <result column="TP" property="tp"/>
    <result column="Magic" property="magic"/>
    <result column="Comment" property="comment"/>
    <result column="timestamp" property="timestamp"/>
</resultMap>

<select id="queryCloseOrderByAccount" resultMap="CloseOrderResultMap">
  select * from closeorder where account in
    <foreach item="item" index="index" collection="list"
             open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

四.当需要根据某个字段分组并将分组数据返回的时候

具体用法参照如下链接
https://www.cnblogs.com/eternityz/p/12284808.html

//dao文件
List<CloseOrderList> selectCloseOrderList();

<resultMap id="customResultMap" type="com.kflh.boxApi.chooseSignalSource.entity.CloseOrderList">
    <id property="account" column="account"/>
    <collection property="closeOrderList" ofType="com.kflh.boxApi.chooseSignalSource.entity.CloseOrder">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="closeorder" jdbcType="INTEGER" property="closeOrder"/>
        <result column="account" jdbcType="INTEGER" property="account"/>
        <result column="symbol" jdbcType="VARCHAR" property="symbol"/>
        <result column="cmd" jdbcType="TINYINT" property="cmd"/>
        <result column="Volume" jdbcType="DOUBLE" property="volume"/>
        <result column="OpenTime" jdbcType="INTEGER" property="openTime"/>
        <result column="OpenPrice" jdbcType="DECIMAL" property="openPrice"/>
        <result column="SL" jdbcType="DECIMAL" property="sl"/>
        <result column="TP" jdbcType="DECIMAL" property="tp"/>
        <result column="Magic" jdbcType="INTEGER" property="magic"/>
        <result column="Comment" jdbcType="VARCHAR" property="comment"/>
        <result column="timestamp" jdbcType="INTEGER" property="timestamp"/>
        <result column="Profit" jdbcType="DECIMAL" property="profit"/>
        <result column="ClosePrice" jdbcType="DECIMAL" property="closePrice"/>
        <result column="Digits" jdbcType="TINYINT" property="digits"/>
        <result column="Storage" jdbcType="VARCHAR" property="storage"/>
    </collection>
</resultMap>

<!--按照指定字段分组并将分组得数据进行返回-->
<select id="selectCloseOrderList"  resultMap="customResultMap">
    select
     <include refid="Base_Column_List"/>
     from closeorder where account in(select account from mt4list_rel)
</select>

五.传参得时候可以使用map进行传参

controller

@Autowired
EaQuanXianService eaQuanXianService;

@RequestMapping(value = "insertWestfieldAccountIndex",method = RequestMethod.GET)
@ResponseBody
public JsonResult insertWestfieldAccountIndex(String param) {
    String[] arr = param.split("@");
    //账号@本地时间@服务器时间@净值@余额
    if (arr.length != 12) {
        throw new ServiceException(ResultEnum.LOSTPARAMS);
    }
    //初始净值
    String equity=eaQuanXianService.selectEquity(Integer.parseInt(arr[0]));
    Double cha=DoubleCalendar.subtract(arr[2],equity);
    Double profitability= DoubleCalendar.divideFloat(cha.toString(),equity);

    Map<String,Object> map=new HashedMap();
    map.put("account",arr[0]);
    map.put("localtime",DateUtil.strToDate(arr[1]));
    map.put("equity",arr[2]);
    map.put("balance",arr[3]);
    map.put("floating",arr[4]);
    map.put("grossProfit",arr[5]);
    map.put("grossLoss",arr[6]);
    map.put("closeVolume",arr[7]);
    map.put("closeOrderNum",arr[8]);
    map.put("tradeVolume",arr[9]);
    map.put("tradeOrderNum",arr[10]);
    map.put("nightInterest",arr[11]);
    map.put("profitability",profitability);
    eaQuanXianService.insertWestfieldAccountIndex(map);
    return new JsonResult();
}

serviceImpl中的方法

@Autowired
EaQuanXianMapper eaQuanXianMapper;

@Override
public int insertWestfieldAccountIndex(Map<String, Object> map) {
    int num = eaQuanXianMapper.insertWestfieldAccountIndex(map);
    if (num <= 0) {
        throw new ServiceException(ResultEnum.INSERTWESTFIELDACCOUNTINDEXFAILED);
    }
    return num;
}

dao文件

int insertWestfieldAccountIndex(Map<String ,Object> map);

xml文件

<insert id="insertWestfieldAccountIndex">
    insert into westfield_account_index values
    (null,#{account},#{localtime},#{equity},#{balance},#{floating},#{grossProfit},
    #{grossLoss},#{closeVolume},#{closeOrderNum},#{tradeVolume},#{tradeOrderNum},
    #{profitability},#{nightInterest})
</insert>

总结:
当从java传map进入mybatis的时候,mybatis需要将map中的具体值取出来,此时就是把map中的key取出来,放入进去即可.也就是说在将参数放入map时得key与mybatis中的取值名称一致
map.put("equity",arr[2])-->mybatis取出来得时候#{equity}

六.常规建立实体类,传实体类或者传具体参数

常规用法

七.传的参数时List但是其中包含的时Map得时候

//dao文件
void insertAccountFilterResultBatch(@Param(value = "list") List<Map<String,Object>> list);

//xml文件
<insert id="insertAccountFilterResultBatch" parameterType="java.util.List">
    insert into account_filter_results values
        <foreach collection="list" index="index" item="item" separator=",">
            (null,#{item.account},#{item.equity},#{item.inMoney},#{item.outMoney},#{item.createTime},
            #{item.totalProfit},#{item.profitRate},#{item.allOrderNum},#{item.allVolumes},
            #{item.historyProfit},#{item.avgVolume},#{item.maxRetracement},'1',now())
        </foreach>
</insert>

总结:
在mybatis的xml文件进行取值得时候,使用foreach标签,签内元素不要使用open及close属性,否则会将所有循环的元素包括进open及close中的大标签中.其中循环体item为Map对象,此时取出其中具体的值得时候需要使用#{item.account},其中account为map中的key

原文地址:https://www.cnblogs.com/eternityz/p/12284827.html