Data Modeling with Hibernate

Introduction

Once Hibernate is configured, the next step is to model your application’s domain using entity classes. These classes represent the tables in your relational database and are mapped using annotations. Hibernate provides a powerful set of annotations to define primary keys, columns, and relationships between entities.

1. Creating an Entity

An entity is a lightweight, persistent domain object. You define an entity class using the @Entity annotation.

@Entity
@Table(name = "users")
public class User {

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

  @Column(name = "username", nullable = false, unique = true)
  private String username;

  @Column(name = "email")
  private String email;

  // Getters and setters
}
  • @Entity: Marks the class as a Hibernate entity.
  • @Table: (Optional) Specifies the table name in the database.
  • @Id: Defines the primary key.
  • @GeneratedValue: Specifies how the primary key is generated.
  • @Column: Maps a field to a column with options like nullable, length, and unique.

2. Primary Key and ID Generation Strategies

Hibernate supports different ID generation strategies:

  • GenerationType.IDENTITY – Auto-increment field (e.g., MySQL, H2)
  • GenerationType.SEQUENCE – Uses a database sequence (e.g., PostgreSQL)
  • GenerationType.TABLE – Uses a table to simulate a sequence
  • GenerationType.AUTO – Lets Hibernate choose the strategy

3. Relationship Mapping

Hibernate allows you to map entity relationships directly using annotations. This is key for modeling complex domain logic.

3.1 One-to-One

@Entity
public class UserProfile {

  @Id
  private Long id;

  @OneToOne
  @JoinColumn(name = "user_id")
  private User user;

  // other fields...
}
  • @OneToOne: Defines a one-to-one relationship.
  • @JoinColumn: Specifies the foreign key column.

3.2 One-to-Many / Many-to-One

@Entity
public class Department {

  @Id
  @GeneratedValue
  private Long id;

  private String name;

  @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
  private List<Employee> employees = new ArrayList<>();
}
@Entity
public class Employee {

  @Id
  @GeneratedValue
  private Long id;

  private String name;

  @ManyToOne
  @JoinColumn(name = "department_id")
  private Department department;
}
  • @OneToMany: A collection in the parent side (e.g., list of employees).
  • @ManyToOne: Reference to the parent entity (e.g., one department).
  • mappedBy: Defines the owning side of the relationship.

3.3 Many-to-Many

@Entity
public class Student {

  @Id
  private Long id;

  private String name;

  @ManyToMany
  @JoinTable(
    name = "student_course",
    joinColumns = @JoinColumn(name = "student_id"),
    inverseJoinColumns = @JoinColumn(name = "course_id")
  )
  private List<Course> courses;
}
@Entity
public class Course {

  @Id
  private Long id;

  private String title;

  @ManyToMany(mappedBy = "courses")
  private List<Student> students;
}

The @JoinTable annotation defines the join table and the foreign keys used to link both sides of the relationship.

4. Additional Mapping Annotations

  • @Enumerated – Maps enums as strings or ordinals.
  • @Temporal – Used with Date/Calendar to define DATE, TIME, or TIMESTAMP.
  • @Lob – Maps large objects like text or binary.
  • @Embedded – Embeds reusable components in entities.

Conclusion

Data modeling is the heart of any Hibernate-based application. By using annotations, you can create powerful mappings between your Java domain and relational schema. Understanding how to model relationships properly will ensure both performance and clarity in your application.

In the next blog, we'll dive into performing actual CRUD operations (Create, Read, Update, Delete) using Hibernate sessions.

Post a Comment

0 Comments