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值