欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis框架实体类字段与数据库表字段不一致导致查询该字段的值一直为null

程序员文章站 2024-03-08 16:46:58
...

实体类如下所示:

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

查询结果:

Mybatis框架实体类字段与数据库表字段不一致导致查询该字段的值一直为null



Mybatis框架实体类字段与数据库表字段不一致导致查询该字段的值一直为null


解决方法

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

Mybatis框架实体类字段与数据库表字段不一致导致查询该字段的值一直为null


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

Mybatis框架实体类字段与数据库表字段不一致导致查询该字段的值一直为null

运行结果:
Mybatis框架实体类字段与数据库表字段不一致导致查询该字段的值一直为null