表中有值,使用@Select查询出来的数据有null值
先描述问题:
表映射类
@Table(name = "sys_user",charset = MySqlCharsetConstant.UTF8,engine = MySqlEngineConstant.InnoDB)
public class User {
@Column(name = "id",isKey = true,type = MySqlTypeConstant.VARCHAR,length = 100,comment = "主键ID")
private String id;
@TableField("user_name")
private String name;
@TableField("user_age")
private Integer age;
@TableField("user_email")
private String email;
}
mapper接口
@Select(value = "select id,user_name,user_age,user_email from sys_user where user_name = #{name}")
List<User> selectUserByName(@Param("name") String username);
调用接口查询
@Test
void testSelectUserByName(){
userServcie.selectUserByName("tom_0").forEach(System.out::println);
}
User(id=3, name=null, age=null, email=null),表中数据是User(id=3, name=tom_0, age=18, email=tom_0@qq.com)
原因分析:这是因为mybatis并不会在使用@Select时按表映射类映射字段和属性,所以查出来的数据除了id,其他都是null,所以这里要把所有要查询的字段名改为和映射类属性一样一一对应,这样就正确了。
//正确答案
@Select(value = "select id,user_name as name,user_age as age,user_email from sys_user where user_name = #{name}")
List<User> selectUserByName(@Param("name") String username);
本文来自博客园,作者:勤匠,转载请注明原文链接:https://www.cnblogs.com/JarryShu/articles/17840438.html