Tutorial

JPA Annotations - Hibernate Annotations

Published on August 3, 2022
author

Pankaj

JPA Annotations - Hibernate Annotations

JPA annotations are used in mapping java objects to the database tables, columns etc. Hibernate is the most popular implement of JPA specification and provides some additional annotations. Today we will look into JPA annotations as well as Hibernate annotations with brief code snippets.

JPA Annotations - Hibernate Annotations

JPA Annotations, Hibernate Annotations Java annotation is a form of metadata that can be added to Java source code. Java annotations can be read from source files. It can also be embedded in and read from class files generated by the compiler. This allows annotations to be retained by JVM at run-time. JPA annotations are not part of standard JDK, so you will get it when you add any implementation framework. For example, below hibernate maven dependency will get you JPA annotations too.

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

JPA Annotations for mapping java object to database table

Let us look at some of the important JPA annotations. Note that these annotations are present in javax.persistence package.

  1. javax.persistence.Entity: Specifies that the class is an entity. This annotation can be applied on Class, Interface of Enums.

    import javax.persistence.Entity;
    
    @Entity
    public class Employee implements Serializable {
    }
    
  2. @Table: It specifies the table in the database with which this entity is mapped. In the example below the data will be stores in the “employee” table. Name attribute of @Table annotation is used to specify the table name.

    import javax.persistence.Entity;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
    }
    
  3. @Column: Specify the column mapping using @Column annotation. Name attribute of this annotation is used for specifying the table’s column name.

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
     
      @Column(name = "employee_name")
      private String employeeName;
    }
    
  4. @Id: This annotation specifies the primary key of the entity.

    import javax.persistence.*;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable { 
      @Id
      @Column(name = "id")
      private int id;
    }
    
  5. @GeneratedValue: This annotation specifies the generation strategies for the values of primary keys.

    import javax.persistence.*;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
      
      @Id
      @Column(name = "id")
      @GeneratedValue(strategy=SEQUENCE, generator="ID_SEQ")
      private int id;
    }
    
  6. @Version: We can control versioning or concurrency using this annotation.

    import javax.persistence.*;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
      @Version
      @Column(name = "version")
      private Date version;
    }
    
  7. @OrderBy: Sort your data using @OrderBy annotation. In example below, it will sort all employees_address by their id in ascending order.

    @OrderBy("id asc")
    private Set employee_address;
    
  8. @Transient: Every non static and non-transient property of an entity is considered persistent, unless you annotate it as @Transient.

     
    @Transient
    Private int employeePhone;
    
  9. @Lob: Large objects are declared with @Lob.

     
    @Lob
    public String getEmployeeAddress() {
        return employeeAddress;
    }
    

The above set of annotation are most commonly used JPA annotations to define an entity.

Hibernate Annotations for Mapping between tables

We have another set of annotations that are used to specify the association mapping between different tables and entities. We will take an example considering the below mentioned scenario.

  • Tables ‘employee’ and ‘employeeDetail’ have one-to-one association and they share the same primary key.
  • Tables ‘communication’ and ‘communicationDetail’ are linked by a foreign key. It is also a one to one association.
  • Tables ‘communication’ and ‘employee’ are linked using a foreign key in many-to-one association with communication being the owner.
  • Tables ‘employee’ and ‘employeeStatus’ are linked through a foreign key in many-to-one association with employee being the owner.

@OneToOne Employee and EmployeeDetail entities share the same primary key and we can associate them using @OneToOne and @PrimaryKeyJoinColumn. In this case the id property of EmployeeDetail is not annotated with @GeneratedValue. The id value of Employee will be used for used for id of EmployeeDetail.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
   
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne(cascade = CascadeType.MERGE)
  @PrimaryKeyJoinColumn
  private EmployeeDetail employeeDetail;
}
 
@Entity
@Table(name = "employeeDetail")
public class EmployeeDetail implements Serializable {
 
  @Id
  @Column(name = "id")
  private int id;
}

Points to note:

Communication and CommunicationDetail are linked through a foreign key, so @OneToOne and @JoinColumn annotations can be used. In snippet mentioned below, the id genereated for Communication will be mapped to ‘communication_id’ column of CommunicationDetail table. @MapsId is used for the same.

@Entity
@Table(name = "communicationDetail")
public class CommunicationDetail implements Serializable {
 
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne
  @MapsId
  @JoinColumn(name = "communicationId")
  private Communication communication;
}
 
@Entity
@Table(name = "communication")
public class Communication implements Serializable {
 
  @Id
  @Column(name = "ID")
  @GeneratedValue
  private Integer id;
 
  @OneToOne(mappedBy = "communication", cascade = CascadeType.ALL)
  private CommunicationDetail communicationDetail;
}

@ManyToOne Many employees can share the same status. So, employee to employeeStatus is a many to one relation. @ManyToOne annotation can be used for the same.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
 
  @ManyToOne
  @JoinColumn(name = "statusId")
  private EmployeeStatus status;
}

@OneToMany Employee to Communication will be a one-to-many relationship. The owner of this relationship is Communication so, we will use ‘mappedBy’ attribute in Employee to make it bi-directional relationship.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
 
  @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
  @OrderBy("firstName asc")
  private Set communications;
}

@PrimaryKeyJoinColumn This annotation is used to associate entities sharing the same primary key.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
   
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne(cascade = CascadeType.MERGE)
  @PrimaryKeyJoinColumn
  private EmployeeDetail employeeDetail;
}

@JoinColumn @JoinColumn annotation is used for one-to-one or many-to-one associations when foreign key is held by one of the entities.

@ManyToOne
@JoinColumn(name = "statusId")
private EmployeeStatus status;

@JoinTable: @JoinTable and mappedBy should be used for entities linked through an association table. @MapsId: Two entities with shared key can be persisted using @MapsId annotation.

@OneToOne
@MapsId
@JoinColumn(name = "communicationId")
private Communication communication;

Hibernate Annotations for inheritance mapping

Now let us try to understand the inheritance mapping annotation in Hibernate. Hibernate supports the three basic inheritance mapping strategies:

  • table per class hierarchy
  • table per subclass
  • table per concrete class

we will consider example for each type.

  1. Table per class hierarchy - single table per Class Hierarchy Strategy.

    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING )
     
    @DiscriminatorValue("Car")
    public class Car {  }
     
    @Entity
    @DiscriminatorValue("BMW")
    public class BMW extends Car {  }
    
  2. Table per class/subclass - joined subclass Strategy.

    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    public class Ship implements Serializable {}
     
    @Entity
    @PrimaryKeyJoinColumn
    public class Titanic extends Ship {}
    
  3. Table per concrete class.

    @Entity
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public class Aeroplane implements Serializable {}
    
  4. @DiscriminatorColumn: As the name suggests this column is the descriminator and this annotation specifies the discriminator column for the SINGLE_TABLE and JOINED Inheritance mapping strategies.

    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING )
    

That’s all for JPA and Hibernate annotations. Reference: JSR 338, Hibernate API Docs

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 9, 2019

Hi Pankaj, I am going through your website for Hibernate , Spring and other technologies as well. Your explanation is very nice and understandable. Can you please add your detailed knowledge on Inheritence mapping of Hibernate. It is missing actually frim hibernate section. Thanks in Advance Md Manzer Imam

- Md Manzer Imam

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 26, 2019

    It should be noted that we should always strive to use JPA annotations instead of the Hibernate ones, unless there is something very specific about the Hiberanate function that is not provided through JPA. And having said that, as soon as JPA does include that functionality, the Hibernate annotations should be changed. For a bit of an overview of some of the differences between JPA and Hibernate, please take a gander at an article I wrote about the subject: https://www.theserverside.com/video/JDBC-vs-ODBC-Whats-the-difference-between-these-APIs

    - Cameron McKenzie

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 11, 2018

      yes,its ultimate sir…thank you

      - shivasharan

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 1, 2018

        very good explanation

        - Nissi

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 22, 2018

          This tutorial is really helpful sir Thank you sir

          - Haris faiz

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Featured on Community

            Get our biweekly newsletter

            Sign up for Infrastructure as a Newsletter.

            Hollie's Hub for Good

            Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

            Become a contributor

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            Welcome to the developer cloud

            DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

            Learn more