Mybatis解决属性名和数据库字段名不一致的问题
例如:
数据库:id name password
属性名:id username password
select * from user where id = #{id}
//类型处理器
select id,name as username,password from user where id = #{id}
解决:
-
起别名(简单粗暴,不推荐使用)
<select id="getUserById" resultType="com.jy.pojo.User"> select id,name as username,password from mybatis.user where id = #{id} </select>
-
结果集映射(重点难点)
resultMaphttps://mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
<!--结果集映射--> <resultMap id="UserMap" type="com.jy.pojo.User"> <!--columu数据库中的字段。property实体类中的属性--> <result column="id" property="id"/> <result column="name" property="username"/> <result column="password" property="password"/> </resultMap> <select id="getUserById" resultMap="UserMap"> select * from user where id = #{id} </select>
- resultmap元素是Mybatis中最重要最强大的元素
- resultMap的设计思想是,ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
ResultMap
的优秀之处——你完全可以不用显式地配置它们- 如果这个世界总是这么简单就好了。。。