程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Mybatis_实体类属性名和数据库字段名不同时的解决方案

发布于2021-05-29 19:48     阅读(975)     评论(0)     点赞(16)     收藏(2)


数据库字段名:
在这里插入图片描述
对应的实体类:

在这里插入图片描述

方案一:

在XML映射文件中使用的resultMap,优点:可以被重复使用。

<resultMap id="BaseResultMap" type="com.dao.entity.UserInfoEntity">
    <!-- 用id属性来映射主键字段 -->
    <id column="_id" jdbcType="VARCHAR" property="id" />
    <!-- 用result属性来映射非主键字段 -->
    <result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>

通过里面的id标签和result标签来建立映射关系,由property和column分别指定实体类属性和数据表的列名。

方案二:

让字段的别名与实体类的属性名相同,优点:操作简单,容易理解。缺点:当这样的语句出现的次数过多的时候,到时冗余代码增多,这些别名不能重用。

<select id="selectAll" resultType="com.dao.entity.UserInfoEntity">
    select _id id, name, age from user
</select>
@Select("select _id id, name, age from user")
List<UserInfoEntity> selectAll();

方案三:

使用Map集合封装结果集,在MyBatis中字段名作为key,字段所对应的数据作为value。优点:可以在多表操作时使用。

<select id="selectUserAll" resultType="java.util.Map">
    select * from user
</select>

方案四:

使用注解@Results和@Result

这两个注解与XML文件中的标签相对应: @Results对应resultMap @Result对应result

@Select("select * from user where name = #{name}")
@Results({
  @Result(property = "id", column = "_id"),
  @Result(property = "name", column = "name")
})
UserInfoEntity getUserByName(@Param("name") String name);
@Select("select * from user where name = #{name}")
@Results(id = "userMap", value = {
  @Result(property = "id", column = "_id"),
  @Result(property = "name", column = "name")
})
UserInfoEntity getUserByName(@Param("name") String name);

@Select("SELECT * FROM user")
@ResultMap("userMap") //公用@Results
List<UserInfoEntity> findUserAll();

方案五:

通过配置属性来完成映射,Mybatis给我们提供了一种映射方式,如果属性的命名是遵从驼峰命名法的,数据列名遵从下划线命名, 那么可以使用这种方式,类似如下:

userName对应user_name;

userId对应user_id;

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
Configuration configuration = new Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);

原文链接:https://blog.csdn.net/qq_43141726/article/details/117332457



所属网站分类: 技术文章 > 博客

作者:飞人出击

链接:http://www.javaheidong.com/blog/article/207251/763058930e187829238f/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)