Hibernate uses annotations or XML configuration files to map class properties (fields) to columns in a database table. This mapping is part of the ORM process, where Hibernate translates Java objects into database records and vice versa. The key components involved in this mapping include:
- Entity Class:
A class annotated with @Entity
represents a table in the database.
2. Table Mapping:
The @Table
annotation specifies the table name if it differs from the class name.
3. Column Mapping:
The @Column
annotation specifies the mapping between a class property and a database column.
4. Primary Key Mapping:
The @Id
annotation designates a property as the primary key for the entity.
How is it used?
- Defining the Entity Class:
Annotate the class with @Entity
and optionally specify the table name using @Table
.
import javax.persistence.Entity; import javax.persistence.Table; @Entity
@Table(name = "employee")
public class Employee {
// Class properties and methods
}
- Mapping Properties to Columns:
Use @Column
to map class properties to specific columns in the database table.
import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Entity; import javax.persistence.Table; @Entity
@Table(name = "employee")
public class Employee {
@Id
@Column(name = "employee_id")
private int id;
@Column(name = "employee_name")
private String name;
@Column(name = "employee_salary")
private double salary;
// Getters and Setters
}
- Mapping Primary Key:
The @Id
annotation is used to mark the primary key field of the entity.
@Id @Column(name = "employee_id") private int id;
- Additional Configurations:
Hibernate provides additional annotations and configurations for advanced mappings, such as @GeneratedValue
for auto-generating primary key values, @OneToMany
for relationships, and @Temporal
for date/time mappings.
Example:
import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Column; import javax.persistence.Id; @Entity
@Table(name = "employee")
public class Employee {
@Id
@Column(name = "employee_id")
private int id;
@Column(name = "employee_name")
private String name;
@Column(name = "employee_salary")
private double salary;
// Constructors, Getters, and Setters
}
Advantages of Using Hibernate for Mapping:
- Consistency: Ensures that your object model remains consistent with the database schema.
- Simplicity: Simplifies database operations by allowing you to work with Java objects instead of raw SQL.
- Flexibility: Provides options for advanced mappings and relationships, making it adaptable to complex data models.
- Maintainability: Reduces boilerplate code and improves the maintainability of the codebase by managing the database interactions through entity classes.