今天第一次尝试使用MyBatis-Plus时,发现在UserController中使用userService.getById(id)
无法得到数据,查看控制台的日志,发现日志中有一条警告2020-09-04 17:36:41.802 WARN 16036 --- [ restartedMain] c.b.m.core.metadata.TableInfoHelper : Warn: Could not find @TableId in Class: com.tp.entity.User.
。
然后查看User实体类,发现MyBatis-Plus代码生成器生成的代码里面没有id属性:
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("m_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
// 数据库中是有id字段的,这里没有生成
private String username;
private String email;
private String password;
}
我有点疑惑,找了一圈,在MyBatis-Plus的代码生成器CodeGenerator
中发现了问题所在。
public class CodeGenerator {
//省略。。。。。。
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id"); /*这一行本来该注释掉的...>_< */
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("m_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
这里,示例代码说过了没有父类实体父类控制器的话不用设置SuperEntityClass
,SuperControllerClass
,SuperEntityColumns
,我当时其实是看到这个的,所以把对应那两行代码注释了,但是我不知怎么的把strategy.setSuperEntityColumns("id");
这行给漏了,没给注释掉,结果自动生成的User实体类里就没有id属性。
既然找到了问题,那么把这行代码注释掉,删掉之前生成的entity,service,mapper,重新跑一遍CodeGenerator
,得到的实体类如下:
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("m_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String username;
private String email;
private String password;
}
这下User实体类就有id属性了,再重新跑userService.getById(id)
就不是null了,日志中的warning也没了。