Hibernate Entity

What is an Entity in Hibernate? An Entity is a representation of a database table in Java POJO class(Plain old java object).

The Java Persistence API (JPA) is a Java specification that bridges the gap between relational databases and object-oriented programming.

ORM: Object-relational mapping

ORM tools like Hibernate, EclipseLink, and iBatis translate relational database models, including entities and their relationships, into object-oriented models.

Defining Entities

In order to define an entity, you must create a class that is annotated with the following :
1. @Entity : The @Entity annotation is a marker annotation, which is used to discover persistent entities.
2. @Table : If you wanted to map this entity to another table.

Now mapping Fields to Columns

1. @Column : You can override the default mapping by using the @Column annotation.
2. @Id  : to designate a field to be the table’s primary key. The primary key is required to be a Java primitive type, a primitive wrapper, such as Integer or Long, a String, a Date, a BigInteger, or a BigDecimal.

Example :

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   address    VARCHAR(150) default NULL,
   PRIMARY KEY (id)
);

Entity equivalent of the above Database Table

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

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

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

    public Employee() {}

    public int getId() {
        return id;
    }

    public void setId( int id ) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName( String first_name ) {
        this.firstName = first_name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName( String last_name ) {
        this.lastName = last_name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Summary

In this section, we learnt how to create a JPA Entity equivalent of a Database Table. Learnt about ORM object relational mapping.
Hope you liked it !