Mybatis当bean里属性名和数据库属性名不一样时如何解决?

方法一共三种

例子

pojo里属性名是               数据库里属性名是:
username ;                       user_name
userage ;                        user_age
方法一: 在写sql时候起别名
<select id="selectByExampleWithBLOBs" resultType ="ResultMapWithBLOBs" parameterType="int" >
    select  user_name username,user_age  userage  from user where id = #{a};
</select>
方法二:在mybatis全局配置文件sqlMapConfig.xml中 开启驼峰命名规则
<configuration>
<settings>
<!--开启驼峰命名规则,可以将数据库中的下划线映射为驼峰命名例如:last_name可以自动映射为lastName
-->
<setting name="mapUnderscorgToCamelCase"  value="true"/】
</settings>
方法三:在mapper的映射文件中使用resultMap自定义映射规则

返回结果集定义为resultmap, 在type里定义为pojo全类名,里面配置列和属性的对应关系

<select id="selectByExampleWithBLOBs" resultMap="myMap" parameterType="int" >
    select  user_name username,user_age  userage  from user where id = #{a};
</select>

<resultMap type="com.atguigu.mybatis.entities.Employee"  id="myMap">
  <!--映射主键-->
  <id column="id"property="id"/>
  <!--映射其他列-->
  <result column="user_name" property="username"/>
  <result column=user_age"   property="userage"/>
</resultMap>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容