Annotation Description Usage Example @EntityMarks a class as a JPA entity @Entity public class User { ... }@TableSpecifies the database table name and schema @Table(name = "users", schema = "app_db")@SecondaryTableMaps entity to multiple tables @SecondaryTable(name = "user_details")@MappedSuperclassDefines common mapping for subclasses @MappedSuperclass public class BaseEntity { ... }@EntityListenersSpecifies callback listener classes @EntityListeners(AuditListener.class)
Annotation Description Usage Example @IdMarks a field as primary key @Id private Long id;@GeneratedValueDefines primary key generation strategy @GeneratedValue(strategy = GenerationType.IDENTITY)@SequenceGeneratorConfigures sequence for ID generation @SequenceGenerator(name = "seq", sequenceName = "user_seq")@TableGeneratorConfigures table for ID generation @TableGenerator(name = "id_gen", table = "id_generator")@EmbeddedIdMarks embedded composite primary key @EmbeddedId private UserId id;@IdClassSpecifies class for composite primary key @IdClass(UserId.class)
Annotation Description Usage Example @ColumnMaps field to database column @Column(name = "user_name", nullable = false)@BasicConfigures basic field mapping @Basic(fetch = FetchType.LAZY, optional = false)@TransientExcludes field from persistence @Transient private transientField;@TemporalMaps Java date/time types to SQL types @Temporal(TemporalType.TIMESTAMP)@EnumeratedMaps Java enums to database @Enumerated(EnumType.STRING)@LobMaps large objects (CLOB/BLOB) @Lob private String largeText;@ConvertSpecifies attribute converter @Convert(converter = BooleanConverter.class)
Annotation Description Usage Example @OneToOneDefines one-to-one relationship @OneToOne(cascade = CascadeType.ALL)@OneToManyDefines one-to-many relationship @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)@ManyToOneDefines many-to-one relationship @ManyToOne(fetch = FetchType.LAZY)@ManyToManyDefines many-to-many relationship @ManyToMany @JoinTable(...)@JoinColumnSpecifies foreign key column @JoinColumn(name = "department_id")@JoinTableConfigures join table for relationships @JoinTable(name = "user_role")@JoinColumnsMultiple join columns for composite keys @JoinColumns({@JoinColumn(...), @JoinColumn(...)})@MapsIdShares primary key with associated entity @MapsId private User user;@PrimaryKeyJoinColumnSpecifies primary key join column @PrimaryKeyJoinColumn(name = "user_id")@ForeignKeyDefines foreign key constraint @ForeignKey(name = "fk_user_dept")
Annotation Description Usage Example @InheritanceDefines inheritance strategy @Inheritance(strategy = InheritanceType.JOINED)@DiscriminatorColumnConfigures discriminator column @DiscriminatorColumn(name = "type")@DiscriminatorValueSpecifies discriminator value @DiscriminatorValue("EMPLOYEE")
Annotation Description Usage Example @EmbeddableMarks class as embeddable component @Embeddable public class Address { ... }@EmbeddedEmbeds a component within an entity @Embedded private Address address;@AttributeOverrideOverrides embedded component attributes @AttributeOverride(name = "street", column = @Column(name = "home_street"))@AttributeOverridesMultiple attribute overrides @AttributeOverrides({...})
Annotation Description Usage Example @ElementCollectionMaps collection of basic/embeddable types @ElementCollection @CollectionTable(...)@CollectionTableConfigures table for element collection @CollectionTable(name = "user_phones")@OrderColumnMaintains order in list collections @OrderColumn(name = "item_order")@MapKeyColumnDefines key column for maps @MapKeyColumn(name = "phone_type")@MapKeyUses entity property as map key @MapKey(name = "id")@MapKeyEnumeratedUses enum as map key @MapKeyEnumerated(EnumType.STRING)@MapKeyTemporalUses date as map key @MapKeyTemporal(TemporalType.DATE)@MapKeyJoinColumnJoin column for map keys @MapKeyJoinColumn(name = "product_id")
Annotation Description Usage Example @NamedQueryDefines reusable JPQL query @NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email")@NamedQueriesMultiple named queries @NamedQueries({@NamedQuery(...), @NamedQuery(...)})@NamedNativeQueryDefines reusable native SQL query @NamedNativeQuery(name = "User.findAll", query = "SELECT * FROM users")@SqlResultSetMappingMaps native SQL query results @SqlResultSetMapping(name = "UserMapping", entities = @EntityResult(...))@EntityResultMaps entity result in native query @EntityResult(entityClass = User.class)@ColumnResultMaps column result in native query @ColumnResult(name = "user_count")@ConstructorResultMaps constructor result in native query @ConstructorResult(targetClass = UserDTO.class, columns = {...})
Annotation Description Usage Example @PrePersistMethod called before entity persistence @PrePersist public void beforeSave() { ... }@PostPersistMethod called after entity persistence @PostPersist public void afterSave() { ... }@PreUpdateMethod called before entity update @PreUpdate public void beforeUpdate() { ... }@PostUpdateMethod called after entity update @PostUpdate public void afterUpdate() { ... }@PreRemoveMethod called before entity removal @PreRemove public void beforeDelete() { ... }@PostRemoveMethod called after entity removal @PostRemove public void afterDelete() { ... }@PostLoadMethod called after entity loading @PostLoad public void afterLoad() { ... }
Annotation Description Usage Example @VersionEnables optimistic locking @Version private Long version;@LockSpecifies lock mode for queries @Lock(LockModeType.PESSIMISTIC_WRITE)
Annotation Description Usage Example @CacheableMarks entity as cacheable @Cacheable
Annotation Description Usage Example @NotNullField cannot be null @NotNull private String name;@SizeSize constraint for strings/collections @Size(min = 2, max = 50) private String name;@Min / @MaxMinimum/maximum value constraints @Min(18) private int age;@EmailValidates email format @Email private String email;@PatternRegex pattern validation @Pattern(regexp = "[A-Za-z0-9]+") private String username;@Past / @FutureDate constraints @Past private Date birthDate;@Positive / @NegativeNumber sign constraints @Positive private BigDecimal amount;@DigitsDigit constraints for numbers @Digits(integer=3, fraction=2) private BigDecimal price;
Annotation Description Usage Example @PersistenceContextInjects EntityManager @PersistenceContext private EntityManager em;@PersistenceUnitInjects EntityManagerFactory @PersistenceUnit private EntityManagerFactory emf;@PersistentContextsMultiple persistence contexts @PersistentContexts({...})@PersistentUnitsMultiple persistence units @PersistentUnits({...})
import jakarta.persistence. * ; // Core JPA annotations
import jakarta.persistence.criteria. * ; // Criteria API
import jakarta.persistence.metamodel. * ; // Metamodel
import jakarta.validation.constraints. * ; // Bean Validation constraints
Enum Type Values Description GenerationTypeAUTO, IDENTITY, SEQUENCE, TABLEPrimary key generation strategies InheritanceTypeSINGLE_TABLE, JOINED, TABLE_PER_CLASSInheritance mapping strategies TemporalTypeDATE, TIME, TIMESTAMPDate/time mapping types EnumTypeORDINAL, STRINGEnum mapping strategies FetchTypeLAZY, EAGERFetch strategies CascadeTypeALL, PERSIST, MERGE, REMOVE, REFRESH, DETACHCascade operation types LockModeTypeREAD, WRITE, OPTIMISTIC, PESSIMISTIC_READ, PESSIMISTIC_WRITELock modes
This table covers the core Jakarta Persistence (JPA) annotations that are part of the official specification. These annotations are standardized and work across different JPA implementations (Hibernate, EclipseLink, OpenJPA, etc.).