mybatis入门教程(五)----参数之返回值类型

MyBatis参数之返回值类型

    MyBatis中的返回值就是Mapper接口中定义的抽象方法的返回值,在mybatis中简化了返回值的操作。

    在SQL映射文件中我们可以直接通过 resultType来指明返回值类型,在这种情况下数据库表中得字段要与实体类的属性名保持一致。

    <!-- 这里的id必须和PostsMapper接口中的接口方法名相同,不然运行的时候也要报错 --> 
    <select id="getPostsById" resultType="Posts" parameterType="int"> 
        select * from posts 
        <if test="_parameter!=0">
        		where id=#{id}
        </if>
        <if test="_parameter==0">
        		limit 0,1
        </if> 
    </select>

        这儿的resultType=“Posts” 中得Posts,直接使用Posts的前提是在MyBatis的配置文件中添加如下别名:

<typeAliases> 
    	   <!-- 实体类的别名 -->
       <typeAlias alias="Posts" type="com.mscncn.batis.model.Posts"/> 
       <typeAlias alias="Pager" type="com.mscncn.batis.model.Pager"/> 
       
    </typeAliases>

        实际上resultType的写法有两种,一种是上面的别名方式,还有一种是直接写Posts类的全限定名。

    <select id="getPostsById" resultType="com.mscncn.batis.model.Posts" parameterType="int"> 
        select * from posts 
        <if test="_parameter!=0">
        		where id=#{id}
        </if>
        <if test="_parameter==0">
        		limit 0,1
        </if> 
    </select>

        上面说的情况很特殊,数据库表字段名与实体类中的属性名保持一致,但是大多数情况下是不同的,那么就需要做一些转换了。


    如果数据库表字段名与实体类的属性名不一致,那么我们有两种方法可以解决:

    A. select语句中使用别名

    <select id="getPostsById" resultType="com.mscncn.batis.model.Posts" parameterType="int"> 
        select posts_id as "id",post_badCount as "badCount" from posts 
        <if test="_parameter!=0">
        		where id=#{id}
        </if>
        <if test="_parameter==0">
        		limit 0,1
        </if> 
    </select>

    B. 使用resultMap元素来管理数据库表字段与实体类属性的对应

   <resultMap type="Posts" id="postList">
   		<id column="posts_id" property="id"/>
   		<result column="posts_title" property="title" />
   		<result column="posts_context" property="context" />
   </resultMap>

        在SQL映射文件中定义resultMap元素,来映射数据库表与实体类的对应关系。

   <select id="getList" resultMap="postList">
   		select * from posts
   </select>

        在select元素中使用resultMap=“postList”,postList就是定义在当前映射文件中resultMap的id值


转载于:https://my.oschina.net/KingPan/blog/266789

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值