Hibernate
Hibernate
1. JDBC code is dependent upon the Database software being used i.e. our
persistence logic is dependent, because of using JDBC. Here we are
inserting a record into Employee table but our query is Database software-
dependent i.e. Here we are using MySQL. But if we change our Database
then this query won’t work.
3. JDBC code is not portable code across the multiple database software.
6. In JDBC, there occurs a Boilerplate problem i.e. For each and every project
we have to write the below code. That increases the code length and reduce
the readability.
To overcome the above problems we use ORM tool i.e. nothing but Hibernate
framework. By using Hibernate we can avoid all the above problems and we can
enjoy some additional set of functionalities.
The source code of Hibernate is also available on the Internet and we can
also modify the code.
Light-weight means:
Hibernate is less in size means the installation package is not big is size.
Hibernate can be used alone or we can use Hibernate with other java
technology and framework.
Non-invasive means:
Hibernate supports Cache Memory whereas JDBC does not support cache
memory.
Hibernate is java based ORM tool that provides framework for mapping
application domain objects to the relational database tables and vice versa.
@Entity
@Table(name = "employee")
@Table(name = "employee")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@OneToOne
@JoinColumn(name = "address_id")
@OneToMany(mappedBy = "employee")
@ManyToOne
@JoinColumn(name = "department_id")
@ManyToMany
@JoinTable(name = "employee_project",
@JoinColumn(name = "department_id")
@JoinTable(name = "employee_project",
The Table Per Hierarchy (TPH) inheritance strategy is one of several approaches
used to map an inheritance hierarchy in object-relational mapping (ORM) systems,
such as Hibernate. This strategy involves mapping an entire class hierarchy to a
single database table, which includes a discriminator column to differentiate
between the various types of entities.
a. In this type suppose I have one parent Entity class and two child
Entity classes.
b. In the database it make only one table from the all classes;
c. Those fields are not present in each other classes that it field make
null;
d. we can’t make columns not null;
e. To mention this type we give the property above the parent class
@Inheritance(strategy =
InheritanceType.SINGLE_TABLE)
f. In this type all the classes are Entity classes so we need mention this
class in the hibernate.cfg.xml
g. If it create one table for all classes then possibility to we can’t
understand which record is from which table for solving this problem
it create a column Dtype automatic Dtypes means discriminated type.
h. It shows which record come from which record.
o Usage: This table contains columns for all fields from all classes in
the hierarchy. Each row corresponds to an instance of a class, with
values in the table’s columns representing the attributes of that class.
2. Discriminator Column:
3. Schema Representation:
o The table will have columns for all the properties of the base class and
all subclasses.
o Base Class: The base class is mapped to the table and includes
common attributes.
1. Simplicity: Since all data is stored in a single table, queries and updates can
be simpler and more straightforward compared to other strategies that
involve multiple tables.
1. Sparse Table: The table can become sparse because it contains columns for
attributes that are only relevant to specific subclasses. This can lead to a lot
of null values.
2. Scalability Issues: As the hierarchy grows, the single table can become very
large, which might impact performance and manageability.
Start by defining the base class with a constructor. This class will be mapped to a
single table that includes a discriminator column to differentiate between
subclasses.
import javax.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
// Default constructor
public Employee() {}
// Parameterized constructor
this.name = name;
return id;
this.id = id;
return name;
}
public void setName(String name) {
this.name = name;
Define subclasses that extend the base class. Each subclass should have its own
constructor and use the @DiscriminatorValue annotation to specify the value for
the discriminator column.
import javax.persistence.*;
@Entity
@DiscriminatorValue("FULL_TIME")
// Default constructor
public FullTimeEmployee() {
super();
// Parameterized constructor
public FullTimeEmployee(String name, double salary) {
super(name);
this.salary = salary;
return salary;
this.salary = salary;
import javax.persistence.*;
@Entity
@DiscriminatorValue("PART_TIME")
// Default constructor
public PartTimeEmployee() {
super();
// Parameterized constructor
super(name);
this.hourlyRate = hourlyRate;
return hourlyRate;
this.hourlyRate = hourlyRate;
3. Configure Hibernate
Make sure your Hibernate configuration is set up to recognize these entities. Here’s
an example using hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</pro
perty>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property
name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Specify annotated classes -->
<mapping class="com.example.Employee"/>
<mapping class="com.example.FullTimeEmployee"/>
<mapping class="com.example.PartTimeEmployee"/>
</session-factory>
</hibernate-configuration>
You can now use these entities in your application code. Here's an example
demonstrating how to use constructors to create and persist entities, and then
retrieve them:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// Create SessionFactory
// Begin transaction
session.beginTransaction();
session.save(fullTimeEmployee);
session.save(partTimeEmployee);
// Commit transaction
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
Example –
import javax.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
@Entity
@Table(name="Employee")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
class Emp{
@Id
int id;
String sname;
public Emp(int id, String sname) {
super();
this.id = id;
this.sname = sname;
}
public Emp() {
super();
}
}
@Entity
@Table(name="Permanant_Emp")
class PEmp extends Emp{
double bonus;
@Override
public String toString() {
return "PEmp [bonus=" + bonus + ", id=" + id + ",
sname=" + sname + "]\n";
}
}
@Entity
@Table(name="Contract_EMP")
class CEmp extends Emp{
double salary;
public CEmp() {
1. For each class of the hierarchy there exist a separate table in the database.
2. Tables are created according to persistent classes but they are treated using
primary and foreign keys so that there will not be any duplicate column in
the relation.
3. While creating the database table foreign key relationship is required
between the parent table and child table.
We need a separate table for the base class and for each derived class.
To get a relation between the base class table and the derived class table we use a
foreign key column in the derived class table
Foreign key column in the derived class table can also be used as a primary key
column for that derived class table to inform the Hibernate that a column of the
table is acting as both primary key and foreign key. We use @PrimaryKeyColumn
annotation for that purpose.
A: Employee Class
// Employee Class
package com.exploit.org;
import javax.persistence.*;
// Annotations
@Entity
@Table(name = "employee")
@Inheritance(strategy = InheritanceType.JOINED)
// Class
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
Example:
// R_Employee Class
package com.exploit.org;
import javax.persistence.*;
// Annotations
@Entity
@Table(name = "r_employee")
@PrimaryKeyJoinColumn(name = "ID")
// Class
Java
// C_Employee Class
package com.exploit.org;
import javax.persistence.*;
// Annotations
@Entity
@Table(name = "c_employee")
@PrimaryKeyJoinColumn(name = "ID")
// Class
D: File: pom.xml
Example:
XML
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
Add the above following dependencies given below in the pom.xml file.
Later, create a hibernate.cgf.xml configuration file and add the entries of mapping
resources.
Example:
XML
<mapping class="com.exploit.org.Employee"/>
<mapping class="com.exploit.org.C_Employee"/>
<mapping class="com.exploit.org.R_Employee"/>
Example 2 –
import javax.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
@Column(name="Second_emp_name")
String Ename;
public SEMP(int id, String ename) {
super();
this.id = id;
Ename = ename;
}
public SEMP() {
super();
}
}
@Entity
@Table(name="Second_Permanant_Employee_1")
class SPEmp extends SEMP{
@Column(name="Second_Permanant_bonus")
double bonus;
public SPEmp() {
super();
}
}
@Entity
@Table(name="Second_Contract_Employee_1")
class SCEmp extends SEMP{
@Column(name="Second_contract_salary")
double salary;
public SCEmp() {
super();
}
}
In this strategy, each subclass table will have the subclass-specific attributes and
the attributes inherited from the parent class.
a. In the table per class suppose we have One parent entity class A, and
two child entity class B,C.
b. Then class A’s all columns comes in the B,C like class A have
firstName, lastName columns and we use table per class then both
columns comes in class B’s and C’s table.
c. Main difference between Table per sub class and Table per class is
only in the table per sub class from the parent class to child class it
comes only parent class as foreign key and in the table per class from
the parent class whole data or all columns comes in the child class
tables.
Example –
import javax.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class ThiredInheritanceDemo {
public static void main(String[] args) {
Configuration cfg = new Configuration();
SessionFactory
sf=cfg.configure("hibernate.cfg.xml").buildSessionFactor
y();
Session se=sf.openSession();
Transaction tr=se.beginTransaction();
TSEMP s1= new TSEMP(1, "AAA");
TSPEmp s2 = new TSPEmp(2, "BBB", 2500.65);
TSCEmp s3 = new TSCEmp(3, "CCC", 2600.56);
se.merge(s1);
se.merge(s2);
se.merge(s3);
tr.commit();
se.close();
}
}
@Entity
@Table(name="Third_Employee_1")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
class TSEMP{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;
@Column(name="Third_emp_name")
String Ename;
public TSEMP(int id, String ename) {
super();
this.id = id;
Ename = ename;
}
public TSEMP() {
super();
}
}
@Entity
@Table(name="Third_Permanant_Employee_1")
class TSPEmp extends TSEMP{
@Column(name="Third_Permanant_bonus")
double bonus;
public TSPEmp() {
super();
}
@Entity
@Table(name="Third_Contract_Employee_1")
class TSCEmp extends TSEMP{
@Column(name="third_contract_salary")
double salary;
public TSCEmp() {
super();
}
}
Mapping –
Hibernate mappings are one of the key features of hibernate . they establish the
relationship between two database tables as attributes in your model. that allows
you to easily navigate the associations in your model and criteria queries.
you can establish either unidirectional or bidirectional i.e you can either model
them as an attribute on only one of the associated entities or on both. it will not
impact your database mapping tables, but it defines in which direction you can use
the relationship in your model and criteria queries.
one to one — it represents the one to one relationship between two tables.
you all must have heard about these relationships. in this article, you will learn
about all relationships using hibernate.
there is a one to many relationship between user and mobile . as one user can have
more than one mobile. and a many to one relationship between mobile and user .
for the one to many relationship, we have to annotate in the same manner as above
with @onetomany to collection type data member . after running the application,
if we look after the table created by hibernate, we will find that hibernate is making
a new table for mapping of user_details table and mobile table( in this example ).
for two-way binding, we annotate the user inside the mobile class
with @manytoone.
you will see the mapping table and its column name will have a default name
generated based on the two tables but to change the default implementation, andwe
will annotate it @jointable and the attribute name in this is to change the name of
mapping table and attribute joincolumns for the primary key of the same class
( user in this case) and inversejoincolumns for the primary key of corresponding
class ( mobile in this case).
d. In the above one student have multiple subjects so we pass the object
of subject class.
e. In the one to many or many to one every time primary key of one
class goes in the multiple values class as foreign key.
f. Now, see when we add the object in to the database
i. we create many values class object.
ii. As per the need we make groups of this object using List.
iii. And when we create an object of one value class that time we
pass this groups to that particular object.
iv. And merge or save one value class object.
v. See the above example we make two groups of subjects as per
the requirement and pass these group to student.
vi. It means One student have group of subjects.
vii. If we delete master object means One value class object it
automatically deletes the salve object also.
One to many by list
Here you will use List type using you can store duplicate records as well you can
maintain the sequence order.
Example –
import java.util.*;
import javax.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
SessionFactory
sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
Session s=sf.openSession();
Transaction tr=s.beginTransaction();
l1.add(s1);
l1.add(s2);
l2.add(s3);
l2.add(s4);
s.merge(ss1);
s.merge(ss2);
s.delete(ss1);
tr.commit();
s.close();
}
}
@Entity
@Table(name="subject_info")
class Subject{
@Id
@Column(name="sub_id")
int id;
@Column(name="subject_name")
String subject;
super();
this.id = id;
this.subject = subject;
public Subject() {
super();
@Entity
@Table(name="student_sub_info")
class Student{
@Id
@Column(name="std_id")
int id;
@Column(name="std_name")
String name;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="student_id")
List<Subject> l1 ;
super();
this.id = id;
this.name = name;
this.l1 = l1;
public Student() {
super();
}
One to Many using set
Example –
import java.util.*;
import javax.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
Session s=sf.openSession();
Transaction tr=s.beginTransaction();
l1.add(s1);
l1.add(s2);
l2.add(s3);
l2.add(s4);
s.merge(ss1);
s.merge(ss2);
s.delete(ss1);
tr.commit();
s.close();
@Entity
@Table(name="subject_info")
class Subject{
@Id
@Column(name="sub_id")
int id;
@Column(name="subject_name")
String subject;
super();
this.id = id;
this.subject = subject;
public Subject() {
super();
}
@Entity
@Table(name="student_sub_info")
class Student{
@Id
@Column(name="std_id")
int id;
@Column(name="std_name")
String name;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="student_id")
Set<Subject> l1 ;
super();
this.id = id;
this.name = name;
this.l1 = l1;
public Student() {
super();
}
}
One to Many by Bag
If the persistent class has list object that contains the entity reference, we need to
use one-to-many association to map the list element. We can map this list object by
either list or bag.
Here, we are using the scenario of Forum where one question has multiple
answers.
Let's see the persistent class that has list objects. In this case, there can be many
answers for a question and each answer may have its own informations that is why
we have used list element (containing Answer objects) to represent a collection of
answers.
import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Department() {}
public Department(String name) {
this.name = name;
import javax.persistence.*;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true)
@ManyToOne
@JoinColumn(name = "department_id")
public Employee() {}
this.employeeId = employeeId;
this.name = name;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
department.addEmployee(emp1);
department.addEmployee(emp2);
session.save(department);
transaction.commit();
session.close();
session.close();
sessionFactory.close();