SpringBoot关于JPA中关于查询findOne和findById

背景

1.SpringBoot升级2.0之后,原本的findOne(String id)方法做了更改,可以使用

@Autowired
private ProductInfoRepository repository;

//这里假设实体类是ProductInfo
ProductInfo productInfo = new ProductInfo();
productInfo.setProductId("111");
Example<ProductInfo> example = Example.of(productInfo);
Optional<ProductInfo> result = repository.findOne(example);

这种方法吧,不知道为什么有的时候查询会失败,但却是也能查

但更多使用findById(String id)方法

Optional<ProductInfo> result = repository.findById(productId);
ProductInfo productInfo = result.get();

2.findById(id).get()使用时,如果数据库中查询无符合条件的记录便会抛出

No value present

的错误,导致自己写的捕获异常的语句失效。

解决方法就是使用isPresent()方法判断有无记录,有则返回记录,无则返回null,如此自己写的查询无结果的异常便能正常触发

具体方法为

Optional<ProductInfo> result = repository.findById(productId);
return result.isPresent()?result.get():null;
 
发布了154 篇原创文章 · 获赞 55 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/weixin_42089175/article/details/98107733
今日推荐