之前的文章记录了传参类型,本文记录一下返回值类型的配置。
返回值属性有两种设置,一种是resultType,一种是resultMap。
resultType适用于返回值是简单类型(String,Integer)或者数据库字段与POJO字段完全一致的情况下,所以属性值一般是某一个pojo类或者简单类型。
如果数据库中的字段在resultType指定的实体类中没有对应的字段名称,那这个值将丢失。如果实例类中的字段名称在数据库中不存在或者不一致,那么最终实体类的这个字段为null(int类型是0,boolean类型为false)
分析记录一下Mapper接口方法不同类型返回值对应的的resultType设置
1,返回值为简单类型。
直接使用resultType=“类型”,如string,Integer等。
2.返回值为List类型。
使用resultType=“list元素的类型”,一般是实体类如User,也可以是Map,对应返回值类型是List<User> List<Map<String,Object>>,不管是哪种,最终结果会根据接口返回值类型自动将多个 resultType指定的类型的元素(User或以一条记录为一个Map)组装成List。
设置:resultType=“com.fkk.model.User”实体类
public List<User> getUser(String age);
<select id="getUser" resultType="com.fkk.model.User">select * from userwhereage = #{age}</select>
设置:resultType=“java.util.Map”
public List<Map<String,Object>> findUserList();
<select id="findUserList" parameterType="int" resultType="java.util.Map">SELECT * FROM user</select>
3.返回值为Map类型。(使用map要注意查询结果的条数,多条会报错)
大概的应用场景是不知道查询的结果有多少字段或者不清楚字段名称。
设置:resultType="java.util.Map"
public Map<String ,Object> findUserById(int id);
<select id="findUserById" parameterType="int" resultType="java.util.Map">SELECT * FROM user where id=#{id}</select>
开发中还会遇到一些情况,比如要实现结果映射成实体类的值,但是数据库改了字段,实体类又因为多处使用不能直接更改,怎么处理??
1.可以通过sql字段设置别名,或者先返回Map类型再进一步转换。
2. 使用resultMap
基于原有的实体类自定义resultMap,重新指定实体字段名与数据库字段名的映射关系,那么在sql方法标签中这要使用resultMap设置返回值类型,属性的值自然就是我们自己定义的resultMap的id值。
<!--2.设置返回数据为resultMap --><resultMap id="userResultMap" type="com.fkk.model.User"><id property="id" column="id_"></id><result property="username" column="username_"></result><result property="sex" column="sex_"></result><result property="birthday" column="birthday_"></result><result property="address" column="address_"></result></resultMap><select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">SELECTid_,username_,sex_,birthday_,address_FROM user WHERE id = #{id}</select>