0% found this document useful (0 votes)
117 views

JPA Annotations - Hibernate Annotations - JournalDev

JPA annotations are used to map Java objects to database tables and columns. Hibernate is a popular implementation of JPA that provides additional annotations. The document discusses common JPA annotations like @Entity, @Table, @Id and @Column for mapping entities and properties. It also covers Hibernate specific annotations for mapping relationships between entities using annotations like @OneToOne, @ManyToOne, @OneToMany, @JoinColumn and more. Finally, it discusses Hibernate annotations for inheritance mapping strategies including table per class hierarchy, table per subclass and table per concrete class.

Uploaded by

M Yasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

JPA Annotations - Hibernate Annotations - JournalDev

JPA annotations are used to map Java objects to database tables and columns. Hibernate is a popular implementation of JPA that provides additional annotations. The document discusses common JPA annotations like @Entity, @Table, @Id and @Column for mapping entities and properties. It also covers Hibernate specific annotations for mapping relationships between entities using annotations like @OneToOne, @ManyToOne, @OneToMany, @JoinColumn and more. Finally, it discusses Hibernate annotations for inheritance mapping strategies including table per class hierarchy, table per subclass and table per concrete class.

Uploaded by

M Yasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

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

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.

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 {

@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 {

@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;

@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;

@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;

@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;

@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;

@Transient : Every non static and non-transient property of an entity is considered


persistent, unless you annotate it as @Transient.

@Transient

Private int employeePhone;

@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:

@PrimaryKeyJoinColumn should be used for associated entities sharing the same primary key.

@JoinColumn & @OneToOne should be mappedBy attribute when foreign key is held by one
of the entities.

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.

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 { }

Table per class/subclass – joined subclass Strategy.

@Entity

@Inheritance(strategy=InheritanceType.JOINED)

public class Ship implements Serializable {}

@Entity

@PrimaryKeyJoinColumn

public class Titanic extends Ship {}

Table per concrete class.


@Entity

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

public class Aeroplane implements Serializable {}

@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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy