Hibernate Tutorial
Core Hibernate
Hibernate Mapping
Hibernate Annotations
Hibernate with Spring Framework
Hibernate with Database
Hibernate Log4j
Inheritance Mapping
Annotations in Hibernate simplify the way you define the mapping metadata. They offer a cleaner and more readable approach compared to XML-based configurations.
This tutorial will cover the basic annotations used in Hibernate:
Make sure you have Hibernate and your JDBC driver dependencies in your pom.xml
file.
Let's create a Student
entity with annotations:
package com.example; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String firstName; private String lastName; private String email; // Constructors, getters, setters, etc. }
@Entity: Specifies that the class is an entity and is mapped to a database table.
@Table: Specifies the name of the database table to be used for mapping. If not given, the class name is used as the default table name.
@Id: Specifies the primary key of an entity.
@GeneratedValue: Specifies how the primary key should be generated. The GenerationType.IDENTITY
strategy means that the DB will auto-increment this field.
Other basic field-level annotations are:
@Column: Specifies a mapped column for a persistent property or field. You can use attributes like name
to specify the column name if it's different from the field name, nullable
to specify nullability, etc.
@Transient: Marks a field as not persistent. It will not be saved to the database.
Hibernate also provides annotations for various object-relational mappings:
@Entity @Table(name="profile") public class Profile { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // bi-directional one-to-one association to Student @OneToOne(mappedBy="profile") private Student student; // other fields, constructors, getters, setters... } @Entity @Table(name="student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // bi-directional one-to-one association to Profile @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="profile_id") private Profile profile; // other fields, constructors, getters, setters... }
In a scenario where one Course
has many Student
instances:
@Entity @Table(name="course") public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // bi-directional many-to-one association to Student @OneToMany(mappedBy="course") private List<Student> students; // other fields, constructors, getters, setters... } @Entity @Table(name="student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // bi-directional many-to-one association to Course @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="course_id") private Course course; // other fields, constructors, getters, setters... }
Suppose a Student
can have many Course
instances and vice versa:
@Entity @Table(name="student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToMany @JoinTable( name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id") ) private List<Course> courses; // other fields, constructors, getters, setters... } @Entity @Table(name="course") public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToMany(mappedBy="courses") private List<Student> students; // other fields, constructors, getters, setters... }
@Temporal: Used with java.util.Date
and java.util.Calendar
. It can be set to DATE
, TIME
, or TIMESTAMP
.
@Enumerated: Used with Java enum types. By default, the enum name is stored as a string. If you want to store the ordinal value, you can use @Enumerated(EnumType.ORDINAL)
.
This tutorial provides an introduction to Hibernate annotations. In real-world applications, you may need to delve deeper into annotations and utilize advanced features of Hibernate. Always refer to the official Hibernate documentation for detailed explanations and best practices.
Annotations in Hibernate mapping:
Hibernate annotations are used to define the mapping between Java entities (classes) and database tables. These annotations simplify the process of defining mappings, eliminating the need for XML configuration.
Entity annotations in Hibernate:
@Entity @Table(name = "products") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "product_id") private Long id; @Column(name = "product_name") private String name; @Column(name = "product_price") private double price; // Getters and setters }
Mapping relationships with annotations in Hibernate:
@Entity @Table(name = "orders") public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id") private Long id; @OneToMany(mappedBy = "order") private List<OrderItem> items; // Other properties and methods } @Entity @Table(name = "order_items") public class OrderItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "item_id") private Long id; @ManyToOne @JoinColumn(name = "order_id") private Order order; // Other properties and methods }
Hibernate annotations for primary key generation:
@Entity @Table(name = "employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "employee_id") private Long id; // Other properties and methods }
Custom annotations in Hibernate entities:
Custom annotations in Hibernate entities are not a common practice. However, you can create custom annotations for specific purposes within your application.
@Entity @Table(name = "custom_entities") @CustomAnnotation public class CustomEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "custom_id") private Long id; // Other properties and methods }
Hibernate validation annotations:
Hibernate provides validation annotations from the Bean Validation API (javax.validation.constraints
). These annotations help ensure that the data stored in entities meets certain criteria.
@Entity @Table(name = "validated_entities") public class ValidatedEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "validated_id") private Long id; @NotNull @Size(min = 2, max = 50) @Column(name = "name") private String name; @Positive @Column(name = "quantity") private int quantity; // Other properties and methods }