# Annotations in Java Spring JPA

In 
Published 2024-01-14

This tutorial explains some annotations used in Java Spring JPA.

Here are some well known annotations used in Java Spring JPA:

# @AttributeOverride

@AttributeOverride : Overrides the default mapping of a field/column.

Example:
@Entity
@AttributeOverride(name = "id", column = @Column(name = "cid"))
public class Car extends Vehicle {
  private String model;
  private String name;

    // standard getters and setters
}

The Car class will have a "cid" (car id) column instead "id" ("id" is a column/attribute in Vehicle class).

# @BatchSize

@BatchSize : Defines size to lazy load a collection of annotated entities.

# @Column(name = "last_name", unique = true)

@Column : Provides additional configuration for a field (column name, length, etc).

@Column(name="FIRST_NAME", nullable=false, length=512)
private String name;

# @CreationTimestamp

@CreationTimestamp : Is a convenient annotation that sets the field value to the current timestamp when the entity is first saved.

# @Entity

@Entity : Marks annotated class as an entity.

# @Embedded

@Embedded : Some fields are taken from another class marked as "@Embeddable".

Example:
@Embedded
private ManagerInfo managerInfo;

# @Embeddable

@Embeddable : The fields from this class could be embedded in another class.

# @EmbeddedId

@EmbeddedId : The fields from embeddable class become the composite primary key (or not) for the entity.

# @Enumerated

To persist an Enum type into a database table.

@Enumerated(EnumType.STRING)
private Rating rating;

# @Fetch

@Fetch : Defines how Hibernate will fetch the data (by select, join or sub-select).

# @Id

@Id : Marks annotated field as a primary key of an entity.

# @GeneratedValue

@GeneratedValue : Provides generation strategy of primary keys.

  • strategy = GenerationType.TABLE -> a table in DB keeps the PK values.
  • strategy = GenerationType.IDENTITY -> could be used when an auto-incremented database column exists in the DB. (not very efficient when using with Hibernate)
  • strategy = GenerationType.SEQUENCE -> when we have a sequence created in the DB for this purpose
  • strategy = GenerationType.AUTO (by default) -> let Hibernate decide what strategy to use. If the Id has the UUID type, the value will be generated using the UUIDGenerator.
Example:
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "post_id_generator")
@SequenceGenerator(name = "post_id_generator", sequenceName = "forum_posts_id_seq", allocationSize = 1)
private Integer id;

# @JoinColumn

@JoinColumn : Used for creating the foreign key for that entity.

# @MapsId

@MapsId : Points to the primary key of referenced entities.

# @ManyToMany

@ManyToMany : Indicates N:M relationship

# @ManyToOne

@ManyToOne : Indicates N:1 relationship, the entity containing annotated field has a single relation to an entity of other class, but the other class has multiple relations.

# @OneToOne

@OneToOne : Indicates 1:1 relationship

# @OneToMany

@ManyToOne : Indicates N:1 relationship

@Entity
public class Class {

    // other columns defined here 
    
    @OneToMany(fetch = FetchType.EAGER)
    private List<Student> students;

# @PersistenceContext

@PersistenceContext : An EntityManger is injected into a Repository class.

@Repository
@Transactional
public class MyRepository {

    @PersistenceContext
    EntityManager entityManager;

    public void persist(Employee emp) {
       //  insert a new Employee into the database
       entityManager.persist(emp);
    }
}

# @Table

@Table : Specify the details of the table that will be used to persist the entity in the database.

@Entity
@Table(name = "EMP")
public class Employee {
    
    // ...
}

In this example the table name is EMP, but the entity is Employee.

# @Temporal

Used to convert java.util.Date or java.util.Calendar to a DATE, TIME, TIMESTAMP table column. Not used since Hibernate 5. Not used for data types from java.time package (OffsetDateTime, LocalTime, LocalDateTime).

The field will be saved as Data type
@Temporal(TemporalType.DATE)
private java.util.Calendar calendarDate;

# @Transient

@Transient : Annotated field is not persistent (is ignored when saved).

# @UpdateTimestamp

@UpdateTimestamp : Is a convenient annotation that sets the field value to the last timestamp when the entity is last updated.