Hibernate Tutorial

Core Hibernate

Hibernate Mapping

Hibernate Annotations

Hibernate with Spring Framework

Hibernate with Database

Hibernate Log4j

Inheritance Mapping

Hibernate - Create POJO Classes

Creating POJO (Plain Old Java Object) classes for Hibernate is straightforward. POJOs in Hibernate are simple Java classes that represent the tables in your database. Here's a step-by-step guide to creating and annotating POJO classes for Hibernate:

1. Basic Structure of a POJO Class

A basic POJO class has:

  • Private member variables corresponding to the columns in the table.
  • A default constructor.
  • Getters and setters for the member variables.
  • Appropriate annotations to map the class and its fields to a database table and columns.

2. Creating a POJO Class with Annotations

For example, consider we have a Student table in the database with id, firstName, and lastName columns. Here's how you'd create a POJO for this:

@Entity  // This tells Hibernate that this is an entity class
@Table(name="student")  // This maps the class to the "student" table in the database
public class Student {

    @Id  // Specifies the primary key of the table
    @GeneratedValue(strategy=GenerationType.IDENTITY)  // Auto-increment
    @Column(name="id")  // Maps the below field to the "id" column in the DB
    private int id;

    @Column(name="first_name")  // Maps the below field to the "first_name" column
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    public Student() { }

    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // Getters and setters...
}

3. Annotations Used in POJO Classes

Here's a brief on the annotations used:

  • @Entity: Marks the class as an entity (i.e., a bean class that represents a table in the database).

  • @Table: Allows you to specify the name of the table in the database that this entity maps to.

  • @Id: Specifies the primary key field of the table.

  • @GeneratedValue: Used to specify how the primary key should be generated. The IDENTITY strategy means it will be auto-incremented.

  • @Column: Maps the annotated field with the specified column name in the DB table.

4. Configuring in hibernate.cfg.xml

After creating the POJO, you must also list it in the Hibernate configuration file (hibernate.cfg.xml) so Hibernate knows about it:

<mapping class="com.yourpackage.Student"/>

5. Considerations

  1. Associations: In real-world scenarios, tables/entities often have relationships like one-to-one, one-to-many, or many-to-many. Hibernate annotations like @OneToOne, @OneToMany, @ManyToMany, and @JoinColumn can be used to define and manage these associations in your POJO classes.

  2. Embeddables: For reusable components or composite keys, you might want to look into @Embeddable and @Embedded annotations.

  3. Lifecycle and Callbacks: Annotations like @PrePersist, @PostPersist, @PreUpdate, etc., can be used to define callback methods that get called at various stages of an entity's lifecycle.

6. Tools

Many IDEs like Eclipse and IntelliJ IDEA, and plugins/tools like Hibernate Tools offer utilities to auto-generate POJOs from existing database tables, which can save a lot of time and effort.

To sum up, creating POJO classes for Hibernate requires an understanding of both your database schema and Hibernate's mapping annotations. Properly created POJOs ensure that your Java application communicates seamlessly with the database through Hibernate.

  1. Generate Hibernate POJO classes:

    Generating Hibernate POJO (Plain Old Java Object) classes involves creating Java classes that represent entities in your application, mapped to database tables.

    @Entity
    @Table(name = "employees")
    public class Employee {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "employee_id")
        private Long id;
    
        @Column(name = "first_name")
        private String firstName;
    
        @Column(name = "last_name")
        private String lastName;
    
        // Other properties and methods
    }
    
  2. Creating entity classes in Hibernate:

    Entity classes in Hibernate are Java classes annotated with @Entity that represent objects persisted in the database.

    @Entity
    @Table(name = "employees")
    public class Employee {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "employee_id")
        private Long id;
    
        @Column(name = "first_name")
        private String firstName;
    
        @Column(name = "last_name")
        private String lastName;
    
        // Other properties and methods
    }
    
  3. Hibernate POJO class example:

    A simple example of a Hibernate POJO class representing an entity.

    @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 productName;
    
        @Column(name = "price")
        private BigDecimal price;
    
        // Other properties and methods
    }
    
  4. Mapping Java classes to database tables in Hibernate:

    Use annotations like @Entity, @Table, @Column, and others to map Java classes to corresponding database tables.

    @Entity
    @Table(name = "departments")
    public class Department {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "department_id")
        private Long id;
    
        @Column(name = "department_name")
        private String departmentName;
    
        // Other properties and methods
    }
    
  • Implementing inheritance in Hibernate entity classes:

    Use inheritance strategies like @Inheritance and @DiscriminatorColumn for entity class hierarchies.

    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "employee_type", discriminatorType = DiscriminatorType.STRING)
    public abstract class Employee {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "employee_id")
        private Long id;
    
        @Column(name = "first_name")
        private String firstName;
    
        @Column(name = "last_name")
        private String lastName;
    
        // Other properties and methods
    }
    
    @Entity
    @DiscriminatorValue("FULL_TIME")
    public class FullTimeEmployee extends Employee {
        // Full-time employee specific properties and methods
    }
    
    @Entity
    @DiscriminatorValue("CONTRACTOR")
    public class Contractor extends Employee {
        // Contractor specific properties and methods
    }
    
  • Annotations for Hibernate entity classes:

    Hibernate provides various annotations like @Entity, @Table, @Column, and more for defining and customizing entity classes.

    @Entity
    @Table(name = "orders")
    public class Order {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "order_id")
        private Long id;
    
        @Column(name = "order_date")
        private LocalDate orderDate;
    
        // Other properties and methods
    }
    
  • Customizing POJO class mapping in Hibernate:

    Customize mapping using annotations and configurations to control how Java classes are mapped to database tables.

    @Entity
    @Table(name = "employees")
    public class Employee {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "employee_id", unique = true, nullable = false)
        private Long id;
    
        @Column(name = "first_name", length = 50, nullable = false)
        private String firstName;
    
        @Column(name = "last_name", length = 50, nullable = false)
        private String lastName;
    
        // Other properties and methods
    }