ジョセフ・ホワン:
私は、以下のような自動生成されたID値を含むエンティティクラスを使用しています
@Entity
@Table(name="BlogUser")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column
private Long id;
@Column
private String username;
私はJpaRepositoryインタフェースを持つUserクラスのidの最大値を取得しよう。これは、サンプルコードです。
UserJpaRepository.findAll().stream().count();
しかし、このラインは、単純な集計値ではなく、ユーザークラスID値の最大値を返します。どのように私は、ストリーム機能付きUserエンティティクラスの最大のid値を得ることができますか?
また:
あなたは使用してそれを見つけることができますStream.max
ように。
Long maxId = UserJpaRepository.findAll().stream()
.map(User::getId) // mapping to id
.max(Comparator.naturalOrder()) // max based on natural comparison
.orElse(Long.MIN_VALUE); // if nothing element is mapped
あるいは単に
long maxId = UserJpaRepository.findAll().stream()
.mapToLong(User::getId) // map to id
.max() // find max
.orElse(Long.MIN_VALUE);