zoukankan      html  css  js  c++  java
  • Mybatis——实体类属性名和数据库字段名不同时的解决方案

    数据库的字段:

    对应的实体类:

     

    方案一:

    在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);
  • 相关阅读:
    CentOS 163 yum 源使用
    RedHat Enterprise Linux 5 安装TFTP服务器和NFS服务器
    Hadoop压缩SNAPPY算法安装
    linux 修改hostname 方法小结
    svnserver配置文件详解
    RedHat启动时sendmail启动慢的解决
    HBase 系统架构
    CentOS 域名解析 配置问题
    yum 安装 gcc
    Missing indirectly referenced artifact com.sun:tools:jar:1.5.0:system 错误
  • 原文地址:https://www.cnblogs.com/nananana/p/8597466.html
Copyright © 2011-2022 走看看