DEV Community

Cover image for How to find an entity in jpa with primary key
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

2

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay