java之mybatis参数映射

相信很多初学者在使用mybatis框架传递参数时都用的使用java的bean封装一个实体类来进行传输,正好之前项目中这种方法比较局限,因此就涉及到了多参数传递以及不知道键值传递的问题,今天总结一下。

首先讲一下参数映射的问题吧,这个主要是要将数据库中搜到的字段封装成实体类,传递到前台。如下,这种方法简洁化了代码,省的每个查询都写对应字段

<sql id="count">
    a.c_id as "id",
    a.name as "name"
</id>
<select id="">
    select
    <include refid="count">
    from test a
</select>

然后进入今天的正题,多参数传递。
1.单参数传递

public List<XXBean> getXXBeanList(String id);  

<select id="getXXXBeanList" parameterType="java.lang.String" resultType="XXBean">

  select t.* from tableName t where t.id= #{id}  

</select>  

其中方法名和ID一致,#{}中的参数名与方法中的参数名一直, 我这里采用的是XXXBean是采用的短名字,

select 后的字段列表要和bean中的属性名一致, 如果不一致的可以用 as 来补充。
2.单个对象

public List<XXBean> getXXBeanList(XXBean user);  

<select id="getXXXBeanList" parameterType="XXBean" resultType="XXBean">

  select t.* from tableName t where t.id= #{id} 
  and t.name=#{name} 

</select>  

单个map(跟单个对象原理一样,只是类型换成hashmap就行)

public List<XXXBean> getXXXBeanList(HashMap map);  

<select id="getXXXBeanList" parameterType="hashmap" resultType="XXBean">

  select 字段... from XXX where id=#{xxId} code = #{xxCode}  

</select>  

3.一个值和一个对象
注意我把sql语句中的parameterType用注解代替了

public List<XXBean> getXXBeanList(@Param("user")XXBean user,@Param("count")int count);  

<select id="getXXXBeanList" resultType="XXBean">

  select t.* from tableName t where t.id= #{user.id} 
  and t.name=#{user.name} 
  and t.count=#{count}

</select>  

4.多个值

public List<XXBean> getXXBeanList(@Param("id")int id,@Param("count")int count);  

<select id="getXXXBeanList" resultType="XXBean">

  select t.* from tableName t where t.id= #{id} 
  and t.count=#{count}

</select>  
public List<XXXBean> getXXXBeanList(String xxId, String xxCode);  

<select id="getXXXBeanList" resultType="XXBean">

  select t.* from tableName where id = #{0} and name = #{1}  

</select> 
public List<XXXBean> getXXXBeanList(List<String> list);  

<select id="getXXXBeanList" resultType="XXBean">
  select 字段... from XXX where id in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
    #{item}  
  </foreach>  
</select>  

5.再说个思想
在项目中正好因为表是代码中创建的,而不是写死的,所以字段并不知道,也就无法插入了,(或者字段随时改变)
所以用到了这种方法:

注意到sql语句中parameterType是否需要,还是在java代码中用注解代替

7.传递表名时用的方法和值是不一样的

public List<XXXBean> getXXXBeanList(@Param("id")int id, @Param("tableName")String tableName); 
<select id="getXXXBeanList" resultType="XXBean">

  select t.* from ${tableName} where id = #{id}  

</select> 

即使更换表名传递参数时也是这样的

<update id="xx">
    alter table ${oldTn} rename to ${newTn}
</update>

附:http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
这篇博客对mybatis的原理介绍的很清楚,有兴趣的可以学习学习。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值