Mybatis-输入和输出映射

输入和输出映射
通过parameterType完成输入映射,通过resultTyperesultMap完成输出映射。
 
1.1 parameterType传递pojo包装对象
可以定义pojo包装类型扩展mapper接口输入参数的内容。
 
需求:
自定义查询条件查询用户信息,需要向statement输入查询条件,查询条件可以有user信息、商品信息。。。。
 
1.1.1 包装类型
Mybatis-输入和输出映射
Mybatis-输入和输出映射
Mybatis-输入和输出映射
Mybatis-输入和输出映射

1.1.2 mapper.xml
 Mybatis-输入和输出映射
Mybatis-输入和输出映射
 
 
1.1.3 mapper.java
Mybatis-输入和输出映射
 Mybatis-输入和输出映射
 
1.1.4 测试
Mybatis-输入和输出映射
 Mybatis-输入和输出映射
 
 
1.1.5 异常
如果parameterType中指定属性错误,异常,找不到getter方法:
 
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'userCusto' in 'class cn.itcast.mybatis.po.UserQueryVo'
### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'userCusto' in 'class cn.itcast.mybatis.po.UserQueryVo'
 
注意:如果将来和spring整合后,不是通过调用getter方法来获取属性值,通过反射强读取pojo的属性值。
 
1.2 resultType
指定输出结果的类型(pojo、简单类型、hashmap..),将sql查询结果映射为java对象 。
 
1.2.1 返回简单类型
mapper.xml
Mybatis-输入和输出映射
Mybatis-输入和输出映射
 
mapper.java
Mybatis-输入和输出映射
Mybatis-输入和输出映射
Mybatis-输入和输出映射
注意:
如果查询记录结果集为一条记录且一列再使用返回简单类型。
 

1.3 resultMap(入门)
resultType :指定输出结果的类型(pojo、简单类型、hashmap..),将sql查询结果映射为java对象 。
使用resultType注意:sql查询的列名要和resultType指定pojo的属性名相同,指定相同属性方可映射成功,如果sql查询的列名要和resultType指定pojo的属性名全部不相同,list中无法创建pojo对象的。
 
resultMap:将sql查询结果映射为java对象。
如果sql查询列名和最终要映射的pojo的属性名不一致,使用resultMap将列名和pojo的属性名做一个对应关系 (列名和属性名映射配置)
 
 
1.3.1 resultMap配置
Mybatis-输入和输出映射
Mybatis-输入和输出映射
 
 
1.3.2 使用resultMap
resultMap和select同一个mapper.xml:
Mybatis-输入和输出映射
Mybatis-输入和输出映射
resultMap和select不同mapper.xml:
例如resultMap在一个namespace为test的mapper.xml中
Mybatis-输入和输出映射
Mybatis-输入和输出映射

1.3.3 mapper.java
 Mybatis-输入和输出映射
Mybatis-输入和输出映射