举个反面例子:

User类中成员变量SpringBoot通过其他的字段查询需注意注意命名的规范性

连接了MySQL数据库,其中在yml文件中写道“jpa: hibernate: ddl-auto: update”,运行后会自动到MySQL创建user表,如下

SpringBoot通过其他的字段查询需注意注意命名的规范性

当我们想使用除了id之外的其他字段进行查询时,我们通常会写一个实现自JpaRepository接口的一个UserRepository接口,此时我们自己创建的UserRepository接口中的方法,一定要命名规范,否则会报如下错误:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract com.example.demo.bean.User com.example.demo.inters.UserRepository.findByUserAccount(java.lang.String)! No property userAccount found for type User!

SpringBoot通过其他的字段查询需注意注意命名的规范性

我的UserRepository接口方法是这样写的:SpringBoot通过其他的字段查询需注意注意命名的规范性

findByUserAccount看起来没什么问题,但是数据库中的user表的字段则是account。所以该方法应该改为findByAccount,如下图:

SpringBoot通过其他的字段查询需注意注意命名的规范性

相关文章: