0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JpaRepositoryのgetOneのEntityNotFoundExceptionにハマった話

Posted at

この間、springboot1.5.xから2.1に上げたんですが、その際にJPAもアップデートされたもんで、

hogeRepository.findById(id);

ってやってたやつがコンパイルエラーになったんですね。

で、以下に書いたようにgetOneに書き換えたんです。
Springboot1.5.x to 2.1.5 Upgrade【コンパイルエラー解消まで】

値がなかった場合は返ってきた値をnullチェックしてたんですが、getOneに変えたことにより、エンティティの値をgetするタイミングでEntityNotFoundExeptionが発生してtry~catchも効かねぇ。。どうしよう。。みたいになってました。
どうやら、getOneは遅延ロードするみたいで、実際にアクセスするときにデータをロードするようです。
なので、今回の用途みたいに、テーブルに値がない場合はどうこうする、みたいなときにはgetOneは向かないみたいです。
orElseでnull返すようにすれば今まで通りになりますね。

Hoge hoge = hoge.Repository.findById(id).orElse(null);
if (hoge == null) {
    
}

どんなふうに使い分けるかは以下のページで詳しく書いてくれてました。
Difference between getOne and findById in Spring Data JPA?

闇雲に置き換えちゃいかんって話でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?