Most Commonly Used Annotations in Hibernate
Introduction to Hibernate Annotations

Hibernate is an open-source Object-Relational Mapping (ORM) framework for Java that provides a way to map Java objects to relational database tables and vice versa.Hibernate simplifies the task of persisting Java objects to a relational database by providing a transparent persistence layer. It maps Java classes to database tables, and Java objects to database rows, without requiring developers to write complex SQL statements or manage database connections and transactions.
@Entity Annotation
The @Entity annotation is used to specify that a Java class is an entity that can be persisted to a database. An entity class represents a table in a relational database, and each instance of the entity class represents a row in the table. The @Entity annotation should be placed on the class declaration.
@Entity
public class Employee {
// class definition
}
@Table Annotation
The @Table annotation is used to specify that instances of the class should be stored in a database table named “employees”.It should be placed on the entity class declaration.
@Entity
@Table(name = "employees")
public class Employee {
// class definition
}
@Id Annotation
The @Id annotation is used to specify the primary key of the entity. Each entity class must have a primary key that uniquely identifies each row in the table. The @Id annotation can be placed on a field or a method level.
@Entity
@Table(name = "employees")
public class Employee {
@Id
private Long id;
// other fields and methods
}
@Column Annotation
The @Column annotation is used to specify the attributes of a column in the database table. It can be used to customize the database column by specifying attributes such as the name, length, nullable, unique, and precision of the column
@Entity
@Table(name = "employees")
public class Employee {
@Id
private Long id;
@Column(name = "first_name", length = 50)
private String firstName;
@Column(name = "last_name", length = 50)
private String lastName;
// other fields and methods
}
@Enumerated Annotation
The @Enumerated annotation is used to specify how an enum values should be persisted in the database. It can be used to specify whether the enum should be persisted as a string or as an integer. The @Enumerated annotation can be used to specify one of two options: EnumType.ORDINAL or EnumType.ORDINAL.
@Entity
@Table(name = "employees")
public class Employee {
@Id
private Long id;
@Enumerated(EnumType.STRING)
private Gender gender;
// other fields and methods
}
public enum Gender {
MALE,
FEMALE
}
@Transient Annotation
The @Transient annotation is used to mark a field or property should not be persisted to the database. Fields or properties marked with the Transientannotation will be ignored by the JPA provider and will not be stored in the database table associated with the entity.
@Entity
@Table(name = "employees")
public class Emploee {
@Id
private Long id;
@Column(name = "first_name", length = 50)
private String firstName;
@Column(name = "last_name", length = 50)
private String lastName;
@Transient
private String fullName;
public String getFullName() {
return firstName + " " + lastName;
}
// other fields and methods
}
@OneToOne Annotation
In Hibernate, a one-to-one relationship between two entities represents a situation where each instance of one entity is associated with exactly one instance of the other entity, and vice versa.
@Entity
@Table(name = "employees")
public class Employee {
@Id
private Long id;
private String firstName;
private String lastName;
@OneToOne(mappedBy = "employee")
private Address address;
// getters and setters
}
@Entity
@Table(name = "addresses")
public class Address {
@Id
private Long id;
private String street;
private String city;
@OneToOne
private Employee employee;
// getters and setters
}
In this example, the Employee class has a OneToOne relationship with the Address class. The address field on the Employee class represents the relationship, and the employee field on the Address class is the inverse relationship.
Cascade Types
Cascade types in Hibernate are used to define how the changes in the state of an entity should propagate to its associated entities.
In other words, when you perform an operation on an entity, such as saving or deleting it, the changes may also need to be applied to its related entities. Cascade types specify which related entities should be affected and how.
Hibernate provides the following cascade types:
CascadeType.ALL: Applies all cascade types to the related entities, including PERSIST, MERGE, REMOVE, REFRESH, and DETACH.
CascadeType.PERSIST: Saves the state of the related entities when the owner entity is saved.
CascadeType.MERGE: Updates the state of the related entities when the owner entity is merged.
CascadeType.REMOVE: Removes the related entities when the owner entity is deleted.
CascadeType.REFRESH: Refreshes the state of the related entities when the owner entity is refreshed.
CascadeType.DETACH: Detaches the related entities when the owner entity is detached.
For example, let’s say you have an Order entity that has a one-to-many relationship with OrderLine entities. If you define the cascade attribute on the Order entity as CascadeType.ALL, then when you save the Order entity, any new OrderLine entities associated with it will also be saved. Similarly, if you delete the Order entity, any associated OrderLine entities will also be deleted.
It’s important to note that cascade types can have performance implications and should be used with caution. Careful consideration should be given to which cascade types are appropriate for a given relationship to ensure that the data integrity is maintained while avoiding unnecessary overhead.
Orphan Removal
In Hibernate, the orphanRemoval attribute is used to automatically remove orphaned entities when they are no longer referenced by their parent entity.
When the orphanRemoval attribute is set to true, any child entities that are no longer referenced by the parent entity will be deleted from the database when the parent entity is updated or removed.
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Address> addresses = new ArrayList<>();
// getters and setters
}
In this example, the addresses attribute in the Employee entity has the orphanRemoval attribute set to true. This means that if any Address entity in the addresses list is removed or updated to no longer reference the Person entity, that Address entity will be removed from the database.
@ManyToOne Annotation
The @ManyToOne annotation is used to specify a many-to-one relationship between two entities. It is used to map a foreign key column in the child table to the primary key column in the parent table.
@Entity
@Table(name = "orders")
public class Order {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
// other fields and methods
}
@Entity
@Table(name = "customers")
public class Customer {
@Id
private Long id;
// other fields and methods
}
@OneToMany Annotation
The @OneToMany annotation is used to specify a one-to-many relationship between two entities. It is used to map a collection of child entities to a single parent entity.
@Entity
@Table(name = "customers")
public class Customer {
@Id
private Long id;
@OneToMany(mappedBy = "customer")
private List<Order> orders;
// other fields and methods
}
@Entity
@Table(name = "orders")
public class Order {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
// other fields and methods
}
@JoinColumn Annotation
In Hibernate, the @JoinColumn annotation is used to specify the column in the database table that is used to join two entities in a relationship.
The @JoinColumn annotation is typically used in conjunction with the @ManyToOne or @OneToOne annotations to define the relationship between two entities. It is used to specify the column that contains the foreign key that references the primary key of the other entity.
@Entity
@Table(name = "employees")
public class Employee {
@Id
private Long id;
private String firstName;
private String lastName;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// getters and setters
}
@Entity
@Table(name = "departments")
public class Department {
@Id
private Long id;
private String name;
// getters and setters
}
In this example, the Employee class has a many-to-one relationship with the Department class, and the @JoinColumn annotation is used to specify the column that contains the foreign key that references the id column of the departments table.
Using the @JoinColumn annotation allows developers to explicitly specify the name of the column used for the join, rather than relying on the default behavior of Hibernate.
@Index Annotation
In Hibernate, the @Index annotation is used to create an index on a database column.
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@Index(name = "idx_employee_id")
private Long id;
@Column(name = "name")
@Index(name = "idx_employee_name")
private String name;
// getters and setters
}
In this example, the Employee entity has two columns - id and name. The @Index annotation is used to create an index on both columns.
The name attribute of the @Index annotation specifies the name of the index. In this example, the indexes are named "idx_employee_id" and "idx_employee_name".
By using the @Index annotation, you can create indexes on one or more columns of a database table. Indexes can improve the performance of queries that filter or sort data based on the indexed columns.
Note that the @Index annotation is optional in Hibernate. If you don't specify the @Index annotation, Hibernate will not create an index for the column.
Conclusion
Hibernate also provides additional features such as lazy loading, caching, and transaction management, which can help improve performance and simplify database operations.
Overall, Hibernate annotations provide a powerful and flexible way to map Java objects to relational database tables and manage data persistence in Java applications.
About the Creator
Kishore Karnatakapu
I'm a passionate software engineer with a good background in full-stack development and expertise in technologies like Java,Spring Boot,Microservices & Angular.Follow for intriguing articles on software engineering & latest industry trends


Comments
There are no comments for this story
Be the first to respond and start the conversation.