MyBatis Review——输入输出映射


一,输入映射


    mybatis的输入映射通过parameterType指定,可以为简单类型,包装类型,hashmap类型。

    

     1,简单类型


                   

<select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
		SELECT * FROM `user` where username like '%${value}%'
	</select>

    2,定义包装类型po



 

<select id="findUserList" parameterType="UserQueryVo" resultType="UserCustom">
		select * from user where user.sex=#{userCustom.sex} and user.username like '%${userCustom.username}%'
	</select>


测试方法:


		//调用mapper方法
		UserQueryVo userQueryVo=new UserQueryVo();
		UserCustom userCustom=new UserCustom();
		userCustom.setSex("1");
		userCustom.setUsername("lhc");
		userQueryVo.setUserCustom(userCustom);
		List<UserCustom> userCustomList=usermapper.findUserList(userQueryVo);
		System.out.println(userCustomList.toString());


  3,使用hashmap

          map中的key要跟xml中占位符名称一致。



二,输出映射


   1,resultType


       使用那个resultType作为输出映射,只有查询出来的列名和pojo中的属性名一致,该列才能映射成功。           

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

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

        3,当查询出来的结果集只有一行一列时候,可以使用简单类型进行输出映射。



   2,resultMap      


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

        

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

 

       1、定义resultMap

 

                         

<!-- 定义resultMap 
		type:resultMap最终所映射的java对象类型,可以使用别名
		id:对resultMap的唯一标识,
		
	-->
	<resultMap type="User" id="userResultMap">
		<!-- id标识的是查询结果集中的唯一标识 
			column:查询出来的列名称
			property:type指定的pojo类型中的属性名
			最终resultMap对column和property作一个映射关系(对应关系)
		-->
		<id column="id_" property="id"/>
		<!-- result对普通列的定义 -->
		<result column="username_" property="username"/>
	</resultMap>


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


<!-- 使用resultMap作为输出映射
		resultMap:指定定义的 resultMap的id,如果这个resultMap在其它的mapper文件,前面需要加上namespace
	 -->
	<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
		SELECT id as id_,username as username_ FROM user  where id=#{value}
	</select>





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值