Mybatis-plus根据id查找返回对象能找到对象但是对象的id值确为空
文章目录
问题描述:
今天在完善我的一个医疗后台管理项目时发现了一个bug,困惑了很久
项目结构mybatisplus+springboot
此时操作的表是患者病历表
其中有三个int类型的字段
我想分别设计3个方法来根据不同的id类型来查找信息
//根据record_id查询
public PatientMedical getPatientMedicalByRecordId(Integer id)
//根据user_id查询
//根据doctor_id查询
实体类
@Schema(description = "患者病历实体")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
//@Data
@TableName("patient_medical_record")
public class PatientMedical implements Serializable {
@Schema(description = "id编号")
@TableId(value = "record_id",type = IdType.AUTO)
private Integer record_id;
// @TableField("user_id")
// private Integer user_id;
// @TableField("doctor_id")
// private Integer doctor_id;
// private String symptoms;
private LocalDateTime created;
private LocalDateTime updated;
}
实现类
@Override
public PatientMedical getPatientMedicalByRecordId(Integer id) {
// PatientMedical patientMedical = patientMedicalMapper.selectById(id);
LambdaQueryWrapper<PatientMedical> lambdaQuery = Wrappers.lambdaQuery();
lambdaQuery.eq(PatientMedical::getRecord_id,id);
PatientMedical patientMedical = patientMedicalMapper.selectOne(lambdaQuery);
System.out.println(patientMedical);
return patientMedical;
}
测试类
public void test() {
PatientMedical patientMedicalByRecordId = patientMedicalServiceImpl.getPatientMedicalByRecordId(1);
System.out.println(patientMedicalByRecordId);
}
接下来先看看数据表中的数据
代码逻辑是没有任何问题的,此时执行测试类查询record_id为1的记录返回结果无疑应该为标红的这一条记录
执行结果
解决方案
根据这个错误情况,能大致判断错误出在sql语句的结果中id无法映射给实体类。问题可能出在实体类字段命名上。在Java中,通常使用驼峰命名法,而数据库字段使用下划线命名法。虽然MyBatis-Plus有自动转换功能,但最好保持一致性
最后解决方案
我将实体类record_id更名为recordid
具体修改:
- 将PatientMedical实体类中的record_id字段重命名为recordId,并添加@TableField(“record_id”)注解,确保与数据库字段正确映射
- 更新了PatientMedicalServiceImpl中的查询方法,使用新的字段名recordId
修改后运行结果
这次返回的PatientMedical对象的record值不为空了,问题解决
感言
虽然这是一个很小的bug,但是我第一次遇到,困惑了很久,掌握的知识告诉我逻辑上是没有错误的,但是问题依旧无法解决,在网上查阅了也没有找到有类似的情景,最终还是要自己去解决,即使是一个小bug,靠自己的琢磨越过了还是很开心的,也许我很长时间都不会忘记这种小事
IT这条路我才出发,能走多远无从得知,但我想我会记录这一路上的见闻
2025年6月28日
成都实训