SpringBoot2.X集成JPA踩坑
JpaRepository中的findOne()方法
findOne()使用示例
许多教程在SpringBoot集成JPA的时候,都会用到JpaRepository中的findOne()方法,如下所示:
@Override
public User findById(Integer id){
return userRepository.findOne(id);
}
User类:
public class User {
private Integer userId;
private String userName;
private String password;
private String phone;
//get/set函数以及构造函数省略
UserRepository类:
import com.jialin.websitedemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer>{
}
问题:
我们先去看一下源码:
public interface QueryByExampleExecutor<T> {
<S extends T> Optional<S> findOne(Example<S> var1);
<S extends T> Iterable<S> findAll(Example<S> var1);
<S extends T> Iterable<S> findAll(Example<S> var1, Sort var2);
<S extends T> Page<S> findAll(Example<S> var1, Pageable var2);
<S extends T> long count(Example<S> var1);
<S extends T> boolean exists(Example<S> var1);
}
可以看到findOne需要传入Example对象,而不是Integer或者String
而在SpringBoot1.5的环境下:
T findOne(ID id);
因此我们也了解了为什么用findOne会报Inferred type ‘S’ for type parameter ‘S’ is not within its bound; should extend 'com.jialin.websitedemo.model.User 的错误了
解决方法:
- 用findById(id).get()替代findOne(id)
- 用getOne(id)替代findOne(id)
扩展
自定义JPA查询方法命名规则
有一篇博客对于命名规则解释的较为全面,包括上图也是出自该博客:jpa方法名命名规则.