JPA Annotations

Himani Prasad
4 min readJun 14, 2023

--

Photo by David Martin on Unsplash

Entity Mapping:

1. @Entity

Java class to tell JPA (Java Persistence API) that this class represents a table in a database.

@Entity
public class User {
// Class code goes here
}

2. @Table

  1. name: Specifies the name of the table in the database. Use this attribute to give a custom name to the table if needed.
  2. schema: Specifies the schema to which the table belongs. A schema is like a folder that holds database objects. Useful when working with databases that support schemas.
  3. catalog: Specifies the catalog to which the table belongs. A catalog is a higher-level container holding schemas. Used in databases with multiple catalogs.
  4. indexes: Allows you to define indexes on the table. Indexes improve query performance by speeding up data retrieval based on specific columns.
  5. uniqueConstraints: Allows you to define constraints on the table to enforce uniqueness of values in specific columns.
@Entity
@Table(name = "users", schema = "public", catalog = "mydb",
indexes = @Index(columnList = "last_name"),
uniqueConstraints = @UniqueConstraint(columnNames = {"email", "username"}))
public class User {
// Class code goes here
}

3. @Column

  • name: Specifies the name of the column in the database table.
  • nullable: Indicates whether the column allows null values or not.
  • unique: Specifies whether the column values should be unique or not.
  • length: Specifies the maximum length of the column for string-based attributes.
  • precision and scale: Used for numeric attributes to specify the precision and scale of the column.
  • insertable and updatable: Controls whether the column should be included in insert and update operations.
@Entity
public class User {
// id and other fields

@Column(name = "first_name", nullable = false, length = 100, unique = true)
private String firstName;

@Column(precision = 10, scale = 2)
private BigDecimal salary;

}

4. @Id

In JPA, the @Id annotation is used to indicate the primary key of an entity, which uniquely identifies each instance of the entity in the database. It is applied to a field or property within the entity class.

When you mark a field or property with @Id, JPA assumes that the corresponding column in the database table is the primary key column.

@Entity
public class User {
@Id
private Long id;
}

5. @GeneratedValue

Here are the attributes of the @GeneratedValue annotation in JPA:

1. strategy:

  1. GenerationType.AUTO: This strategy allows the persistence provider to choose an appropriate generation strategy based on the underlying database. It may use identity columns, sequences, or other mechanisms depending on the database capabilities.
  2. GenerationType.IDENTITY: This strategy relies on an auto-incremented database column to generate primary key values. The database is responsible for generating the values, and it typically uses identity columns or similar mechanisms.

However, when using database-generated primary keys, Hibernate cannot take advantage of JDBC batching because it needs to perform the insert immediately to obtain the primary key value.

To overcome this drawback and still benefit from JDBC batching, you can consider using alternative primary key generation strategies, such as sequence generators. Sequence generators allow Hibernate to obtain a set of primary key values in advance from the database sequence and assign them to the entities. This enables Hibernate to use JDBC batching for inserting multiple entities with pre-allocated primary key values, improving performance.

3. GenerationType.SEQUENCE: This strategy uses a database sequence to generate primary key values. It involves obtaining the next value from the sequence and using it as the primary key for the entity.

To use GenerationType.SEQUENCE, you can simply annotate your primary key field with @GeneratedValue(strategy = GenerationType.SEQUENCE). By default, Hibernate will request the next value from its default sequence. However, you can customize this behavior by referencing a specific sequence generator using the generator attribute of the @GeneratedValue annotation. You can define the sequence generator using the @SequenceGenerator annotation, specifying the name of the generator, the name and schema of the database sequence, and the allocation size of the sequence.

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "book_generator")
@TableGenerator(name = "book_generator", table = "id_generator", schema = "bookstore")
private Long id;

4. GenerationType.TABLE: This strategy uses a separate database table to generate primary key values. The table stores a value that is incremented and used as the primary key for each entity.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Other properties and methods
}

2. generator:

Specifies the name of the generator to use when the strategy is set to GenerationType.SEQUENCE or GenerationType.TABLE. The generator must be defined using the @SequenceGenerator or @TableGenerator annotation, respectively.

 @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

6. @Embedded

The @Embedded annotation in JPA is used to indicate that an attribute within an entity should be treated as an embedded object. It allows you to map complex types or value objects as part of the entity's table, rather than creating a separate table for each attribute.

When you mark an attribute with @Embedded, it means that the attribute's value will be stored directly in the same table as the entity that contains it, instead of creating a separate table for the embedded object.

@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Embedded
private Address address;
}
@Embeddable
public class Address {
private String street;
private String city;
private String state;
private String postalCode;
// Constructors, getters, and setters for the Address class
// ...
}

6. @MappedSuperclass

lets you create a shared superclass that can be used by multiple entity classes. This superclass doesn’t have its own table in the database, but it provides common attributes or behavior that can be inherited by its subclasses. By using @MappedSuperclass, you can avoid repeating the same code in multiple classes and promote reusability, making your code cleaner and more efficient.

@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {

}
@Entity
@Table(name = "customers")
public class Customer extends BaseEntity {

}

--

--