Mybatis框架實體類字段與數據庫表字段不一致導致查詢該字段的值一直爲null

實體類如下所示:

public class BasicInfo {
    private Integer basic_id;
    private String name;
    private String gender;
    private Integer age;
    private String address;
    private String email;
    private String phone;
    private String school;
    private String introduce;

    //……(此處省略setter和getter方法)
}

實體類映射的數據庫表如下所示:

create table `basic_info`
 (
      `basic_id` int not null auto_increment,
      `name` varchar(16),
      `gender` varchar(4) ,
      `age` int default '0',
      `address` varchar(64),
      `email` varchar(32),
      `tel` varchar(16),
      `school` varchar(64),
      `introdece` varchar(1024),
      `user_id` int,

  primary key (`basic_id`),
  key `fk_basicinfo_account` (`user_id`),

  constraint `fk_basicinfo_account` foreign key (`user_id`) references `account` (`id`)

) engine=InnoDB default charset=utf8 |

使用Mybatis查詢配置如下所示

<select id="queryById" parameterType="int" resultType="BasicInfo">
        select basic_id,name,gender, age,school,tel
        from basic_info
        where basic_id = #{id}
</select>

主要查詢java代碼:

@Override
    public BasicInfo queryById(Integer id) {
        BasicInfo basicInfo = null;
        SqlSession session = MybatisSessionManage.getSqlSessionAutoCommit();
        basicInfo = session.selectOne("basicinfo.queryById", id);
        return basicInfo;
    }

查詢結果:

這裏寫圖片描述



這裏寫圖片描述


解決方法

方法1
查詢中含有表字段與對象字段不對應的,可以在查詢語句用as 對象字段名解決字段不一致不自動封裝的問題

<select id="queryById" parameterType="int" resultType="BasicInfo">
        select basic_id,name,gender, age,school,tel as phone
        from basic_info
        where basic_id = #{id}
</select>

這裏寫圖片描述


方法2
修改select元素中resultType屬性 爲 resultMap屬性並創建返回的map類型

<resultMap id="basicInfoMapper" type="BasicInfo">
        <id column="basic_info" property="basic_id" />
        <result column="name" property="name" />
        <result column="gender" property="gender" />
        <result column="age" property="age" />
        <result column="address" property="address" />
        <result column="email" property="email" />
        <result column="tel" property="phone" />
        <result column="school" property="school" />
        <result column="introduce" property="introduce" />
</resultMap>

<select id="queryByIdAndMapper"  resultMap="basicInfoMapper" parameterType="int">
        select basic_id,name,gender, age,school,tel
        from basic_info
        where basic_id = #{id}
</select>

這裏寫圖片描述

運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章