注解开发mybatis的mapper属性和字段不对应问题@Results—resultMap
2017-10-10 18:02
477 查看
注解开发—mybatis的mapper属性和字段不对应问题@Results—resultMap
Mybatis给我们提供了一种映射方式,如果属性的命名是遵从驼峰命名法的,数据列名遵从下划线命名。MyBatis支持使用注解来配置映射语句,不再需要在XML配置文件中配置。学习内容
@Results对应resultMap@Result对应result
这两个注解是应用在方法的级别上的,也就是在mapper方法。
@Results结果映射
mybatis不能通过@Column注解或者直接使用实体类的属性名作为数据列名,而是需要自己指定实体类属性和数据表中列名之间的映射关系解决方案
我们可以将查询结果通过别名与JavaBean属性映射起来。当然使用@Results注解也可以将指定列与指定JavaBean属性映射起来执行SELECT查询的:
@Select("SELECT * FROM `wx_message_config` WHERE `content_key_words` IS NOT NULL AND LENGTH(content_key_words) > 0") @Results({ @Result(property = "msgType", column = "msg_type"), @Result(property = "eventType", column = "event_type"), @Result(property = "eventKey",column = "event_key"), @Result(property = "contentKeyWords",column = "content_key_words") }) List<WxMessageConfig> queryAllKeyWords(); @Select("SELECT * FROM `wx_message_config` WHERE `id` = #{id}") @Results({ @Result(property = "msgType", column = "msg_type"), @Result(property = "eventType", column = "event_type"), @Result(property = "eventKey",column = "event_key"), @Result(property = "contentKeyWords",column = "content_key_words") }) WxMessageConfig queryKwById(int id);
由于注解是针对方法的,对于Mapper中的每个操作数据库的方法都必须有相同的注解完成映射关系的建立,导致很多是重复的。
共用@Results——resultMap
为了解决重复使用,那就要让他变成一个有id的整体,其他地方要用就直接调用@ResultMap(“id”)
@Result中通过id属性引用这个resultMap
@Select("SELECT id, name, password FROM user WHERE id = #{id}") @Results(id = "userMap", value = { @Result(column = "id", property = "id", javaType = Integer.class), @Result(column = "name", property = "name", javaType = String.class), @Result(column = "password", property = "password", javaType = String.class) }) User findById(Integer id); @Select("SELECT * FROM user") @ResultMap("userMap") List<User> fingAll();
这个本地测试好像没有成功
通过使用在SQL语句中定义别名完成映射
@Select("select user_name as userName, user_id as userId from t_user where user_name = #{userName}") User getUserByName(@Param("userName") String userName);
参考1
参考2
谢谢。
相关文章推荐
- mybatis入门字段与属性不对应问题(三)
- mybatis resultMap 的日期字段无法获取时分秒的问题
- MyBatis关联查询,表字段相同,resultMap映射问题的解决办法
- MyBatis关联查询,表字段相同,resultMap映射问题的解决办法
- mybatis resultMap 的日期字段无法获取时分秒的问题
- MyBatis关联查询,表字段相同,resultMap映射问题的解决办法
- mybatis resultMap 的日期字段无法获取时分秒的问题
- MyBatis的一系列问题的处理(遍历Map集合和智能标签和属性和字段不一样的解决办法 和sql片段)(三)
- MyBatis关联查询,表字段相同,resultMap映射问题的解决办法
- SpringMVC+Spring+Mybatis 环境搭建问题记录(注解开发)
- Mybatis resultMap空值映射问题解决
- MyBatis使用@MapKey注解接收多个查询记录到Map中,以便方便地用get()方法获取字段的值
- MyBatis学习-----解决在"数据表中字段与自己定义的属性类的属性字段不相同“的情况下的问题
- 深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap
- Mybatis resultMap空值映射问题解决
- 深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap
- mybatis的mapper的配置文件的resultMap元素的用法和作用
- mybatis使用association的resultMap方式进行映射少数据问题
- Struts注解开发问题2——The Result type [json] which is defined in the Result annotation on the class
- SpringMVC+MyBatis开发中指定callSettersOnNulls,可解决返回字段不全的问题