• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Y-wee
博客园    首页    新随笔    联系   管理     

mybatis中实体类属性与数据库不一致解决方法

mybatis中实体类属性与数据库不一致解决方法

当实体类属性和数据库不一致时,使用mybatis查询数据库返回实体类自动封装就会出现问题。针对这种情况,有两种解决方案。

1、使用别名查询

<!-- 配置查询所有操作 --> 
<select id="findAll" resultType="com.itheima.domain.User">
select id as userId,username as userName,birthday as userBirthday,
sex as userSex,address as userAddress from user
</select>
  • 优点:查询效率高
  • 缺点:如果我们的查询很多,都使用别名的话写起来很麻烦

2、定义resultMap

resultMap 标签可以建立查询的列名和实体类的属性名称不一致时建立对应关系。从而实现封装。在 select 标签中使用 resultMap 属性指定引用即可。同时 resultMap 可以实现将查询结果映射为复杂类型的 pojo,比如在查询结果映射对象中包括 pojo 和 list 实现一对一查询和一对多查询。

<!-- 建立User实体和数据库表的对应关系
type属性:指定实体类的全限定类名
id属性:给定一个唯一标识,是给查询select 标签引用的。--> 
<resultMap type="com.itheima.domain.User" id="userMap"> 
    <id column="id" property="userId"/>
    <result column="username" property="userName"/>
    <result column="sex" property="userSex"/>
    <result column="address" property="userAddress"/>
    <result column="birthday" property="userBirthday"/>
</resultMap>
<!--id 标签:用于指定主键字段
result 标签:用于指定非主键字段
column 属性:用于指定数据库列名
property 属性:用于指定实体类属性名称-->

<!-- 配置查询所有操作-->
<select id="findAll" resultMap="userMap">
	select * from user
</select>
  • 优点:代码书写简洁,提高开发效率
  • 缺点:查询效率低
记得快乐
posted @ 2020-10-16 15:19  Y-wee  阅读(675)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3