#
Annotations in Java Spring JPA
This tutorial explains some annotations used in Java Spring JPA.
Info
Java annotations are metadata (data about data) provided to the compiler and JVM. An annotation could be on classes, interfaces, variables, methods, or fields level. Annotations do not impact the execution of the code.
Here are some well known annotations used in Java Spring JPA:
#
@AttributeOverride
@AttributeOverride
: Overrides the default mapping of a field/column.
@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".
@Embedded
private ManagerInfo managerInfo;
ManagerInfo attributes will be taken/added to the current Entity. ManagerInfo class must be annotated using @Embeddable.
#
@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;
Info
EnumType.STRING is to persist the name, EnumType.ORDINAL is to persist an integer value.
#
@Fetch
@Fetch
: Defines how Hibernate will fetch the data (by select, join or sub-select).
@Fetch(FetchMode.JOIN)
: collections are fetched in a single query.@Fetch(FetchMode.SELECT)
: Hibernate behaves in a lazy manner to fetch child collections.@Fetch(FetchMode.SUBSELECT)
: separate queries are executed for the parent entity and the child collection.
#
@Id
@Id : Marks annotated field as a primary key of an entity.
Info
For a simple PK, we need to have a primitive or a primitive wrapper.
#
@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 purposestrategy = 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.
@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;
Info
We can specify also the fetch type EAGER or LAZY.
#
@PersistenceContext
@PersistenceContext
: An EntityManger is injected into a Repository class.
Info
- Entity manager is used to read, delete and write an entity from/into a database.
- @PersistenceContext takes care to create a unique EntityManager for every thread.
@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).
@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.