• 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);
  • 相关阅读:
    一些端口
    outlook 的微软手册
    目录摘要
    L2TP的包过滤规则
    outlook 的外出时助理程序对外部邮箱不起作用。1个解决办法和另外一个可能性
    用editplus 正则表达式修改联系人表
    Cisco NAT的理解。
    outlook 2003 无法记住密码
    ERD commander 2005的下载地址。
    outlook 2003启用日志记录排除故障。
  • 原文地址:https://www.cnblogs.com/nananana/p/8597466.html
Copyright © 2020-2023  润新知