zoukankan      html  css  js  c++  java
  • 关于mybatis中的实体类属性与数据库中的列名不一致的两种解决方法

    1.我们都知道,在mybatis中写实体类的时候,是按照数据库中的列名来给实体类定义属性的,举个例子:

    public class User implements Serializable {
        private Integer id;
        private String username;
        private String address;
        private String sex;
        private Date birthday;
    }

     2.但是,如果我们在定义实体类的时候,实体类中的属性与数据库列名不一致呢?比如:

    public class User implements Serializable {
        private Integer userId;
        private String userName;
        private String userAddress;
        private String userSex;
        private Date userBirthday;
    }

    3.这个时候就有两种解决办法:

    方法一:在sql语句中给数据库中的字段起别名:

     <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>

    这样就能够把查询到的数据与实体类的属性对应起来,并封装回User类的对象了,缺点是每次都要起别名,消耗精力,优点是执行效率高。

    方法二:给实体类和数据库建立对应关系:

        <resultMap id="userMap" type="com.itheima.domain.User">
    <!--        主键字段的对应-->
            <id property="userId" column="id"></id>
    <!--        非主键字段的对应-->
            <result property="userName" column="username"></result>
            <result property="userSex" column="sex"></result>
            <result property="userBirthday" column="birthday"></result>
            <result property="userAddress" column="address"></result>
        </resultMap>

    然后在sql语句中将resultType设置为"userMap"即可;

     <!--    查询所有-->
        <select id="findAll" resultType="userMap">
            select * from user ;
        </select>

    这种方法写起来代码量少,但是因为添加了resultMap对应这一环节,执行效率不高。

  • 相关阅读:
    SQL基础学习_03_数据更新
    SQL基础学习_02_查询
    SQL基础学习_01_数据库和表
    HCA数据下载
    Multiclonal Invasion in Breast Tumors Identified by Topographic Single Cell Sequencing
    gg_pie
    ggnetwork
    ggplot2画简单的heatmap
    简单R语言爬虫
    突变数据清洗
  • 原文地址:https://www.cnblogs.com/iceywu/p/12343648.html
Copyright © 2011-2022 走看看