How to find an entity in jpa with primary key

Use the find method of the EntityManager, where the primary key is provided as the second parameter:

@Stateless
public class PartnerRepository {

  @Inject private EntityManager em;

  public Optional<Partner> find(String partnerNumber) {
    return Optional.ofNullable(em.find(Partner.class, partnerNumber));
  }
}

Enter fullscreen mode Exit fullscreen mode

The entity looks something like the following, with partnerNumber as primary key:

@Entity
@Access(AccessType.FIELD)
@Table(name = "T_PARTNER")
public class Partner {

  @Id
  @NotNull
  @Column(name = "PARTNER_NUMBER", nullable = false)
  private Integer partnerNumer;

  //other fields ignored for readability
}

Enter fullscreen mode Exit fullscreen mode


Shared ️ from Codever. use the copy to mine functionality to add it to your personal snippets collection.

原文链接:How to find an entity in jpa with primary key

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容