您的位置:首页 > 编程语言 > Java开发

MyBatis入门【五】输入映射、输出映射

2018-01-30 01:01 267 查看

输入映射

通过parameterType指定输入参数的类型,类型可以是简单类型、hashmap、pojo包装类型

包装类示例

public class UserQueryVo{
//在这里包装所需要的查询条件

//用户查询条件
private UserCustom getUserCustom(){
return userCustom;
}
public void setUserCustom(UserCustom userCustom){
this.userCustom = userCustom;
}

//可以包装其他的查询条件,订单、商品
}


mapper.xml文件示例:

<!--用户信息综合查询-->
<!--    #{userCustom.sex} :取出pojo包装对象中性别值-->
<select id="findUserList" parameterType="UserQueryVo全路径/别名" resultType="包装类型全路径或别名">
select * from user where user.id=#{属性.属性(对象组合)} and user.username like '%${属性(单纯的属性,Java基本类型)}%'
</select>


mapper.java:

//用户信息综合查询
public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;


输出映射

1、resultType

2、resultMap

resultType

使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。

如果查询出来的列名和pojo中的属性名全部不一致,没有创建pojo对象。

只要查询出来的列名和pojo中的属性有一个一致,就会创建pojo对象

resultMap详解

mybatis中使用resultMap完成高级输出结果映射

resultMap使用方法:

如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间做一个映射关系

1、定义resultMap

mapper.xml文件中

定义resultMap:

<!-- type:resultMap最终所映射的Java对象类型,可以使用别名 -->
<!-- id:对resultMap的唯一标识、 -->

<resultMap type="user" id="userResultMap">
<!-- id表示查询结果集中唯一标识  column: 查询出来的列名 property:type指定的pojo类型的属性名   最终resultMap对column和property做一个映射关系(对应关系) -->
<id column=""  property=""/>
<!-- result:对普通列名进行映射定义    column: 查询出来的列名 property:type指定的pojo类型的属性名   最终resultMap对column和property做一个映射关系(对应关系) -->
<result column=""  property=""/>
</resultMap>


mapper.java文件中

<!-- 根据id查询用户信息,使用resultMap -->
public User findUserByIdResultMap(int id) throws Exception;


2、使用resultMap作为statement的输出映射类型

<!-- 使用resultMap进行输出映射-->
<!-- resultMap:指定定义的resultMap的id,如果resultMap在其他的mapper文件中,前边需要加namespace-->
<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
SELECT id id_,username username_ FROM USER WHERE id =#{value}
</select>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java ee java MyBatis SSM