0% found this document useful (0 votes)
31 views46 pages

Hibernate

Uploaded by

thirosul
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)
31 views46 pages

Hibernate

Uploaded by

thirosul
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/ 46

Hibernate

Introduction to Hibernate Framework

Hibernate is used to overcome the limitations of JDBC like:

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.

2. If working with JDBC, changing of Database in middle of the project is very


costly.

3. JDBC code is not portable code across the multiple database software.

4. In JDBC, Exception handling is mandatory. Here We can see that we are


handling lots of Exception for connection.
5. While working with JDBC, There is no support Object-level relationship.

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.

About Hibernate Framework PUSHING FACTOR TOWARD HIBERNATE

JDBC code is dependent upon the Database software being used


changing of Database in middle of the project is very costly.
not portable code across the multiple database software.
Exception handling is mandatory
no support Object-level relationship.
a Boilerplate problem ex- Try Catch block
Hibernate is a framework which provides some abstraction layer, meaning that
the programmer does not have to worry about the implementations, Hibernate does
the implementations for you internally like Establishing a connection with the
database, writing query to perform CRUD operations etc.
It is a java framework which is used to develop persistence logic. Persistence
logic means to store and process the data for long use. More precisely Hibernate is
an open-source, non-invasive, light-weight java ORM(Object-relational mapping)
framework to develop objects which are independent of the database software and
make independent persistence logic in all JAVA, JEE.

Framework means it is special install-able software that provides an abstraction


layer on one or more technologies like JDBC, Servlet, etc to simplify or reduce the
complexity for the development process.

Open Source means:

 Hibernate framework is available for everyone without any cost.

 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 does not require any heavy container for execution.

 It does not require POJO and POJI model programming.

 Hibernate can be used alone or we can use Hibernate with other java
technology and framework.

Non-invasive means:

 The classes of Hibernate application development are loosely coupled


classes with respect to Hibernate API i.e. Hibernate class need not
implement hibernate API interfaces and need not extend from Hibernate API
abstraction layer ( IMPLEMENTATION BY HIBERNATE)
classes.
java framework which is used to develop persistence logic (store and process the data for long use)
Open Source
Functionalities
Light-weight supported by Hibernate framework
Non-invasive
Auto DDL(create,update,delete)
Auto Primary key generation
HQL
Exception Handling is not mandatory,
supports Cache Memory
ORM tool
 Hibernate framework support Auto DDL operations. In JDBC manually we
have to create table and declare the data-type for each and every column.
But Hibernate can do DDL operations for you internally like creation of
table,drop a table,alter a table etc.

 Hibernate supports Auto Primary key generation. It means in JDBC we


have to manually set a primary key for a table. But Hibernate can this task
for you.

 Hibernate framework is independent of Database because it supports HQL


(Hibernate Query Language) which is not specific to any database,
whereas JDBC is database dependent.

 In Hibernate, Exception Handling is not mandatory, whereas In JDBC


exception handling is mandatory.

 Hibernate supports Cache Memory whereas JDBC does not support cache
memory.

 Hibernate is a ORM tool means it support Object relational mapping.


Whereas JDBC is not object oriented moreover we are dealing with values
means primitive data. In hibernate each record is represented as a Object but
in JDBC each record is nothing but a data which is nothing but primitive
values.

What is the application of Hibernate in Java?

Hibernate is java based ORM tool that provides framework for mapping
application domain objects to the relational database tables and vice versa.

List out of Annotation which are used in hibernate

1. @Entity: Specifies that a class is an entity and is mapped to a database


table.

@Entity

@Table(name = "employee")

public class Employee { ... }


2. @Table: Specifies the name of the database table to be used for mapping.

@Table(name = "employee")

3. @Id: Marks a field as the primary key of the entity.

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

4. @GeneratedValue: Provides the strategy for generating primary key values


(e.g., auto-increment, sequence).

@GeneratedValue(strategy = GenerationType.IDENTITY)

5. @Column: Specifies the details of the column to which a field is mapped.

@Column(name = "first_name", nullable = false)

private String firstName;

6. @OneToOne: Defines a one-to-one relationship between two entities.

@OneToOne

@JoinColumn(name = "address_id")

private Address address;

7. @OneToMany: Defines a one-to-many relationship between two entities.

@OneToMany(mappedBy = "employee")

private List<Project> projects;

8. @ManyToOne: Defines a many-to-one relationship between two entities.

@ManyToOne

@JoinColumn(name = "department_id")

private Department department;


9. @ManyToMany: Defines a many-to-many relationship between two
entities.

@ManyToMany

@JoinTable(name = "employee_project",

joinColumns = @JoinColumn(name = "employee_id"),

inverseJoinColumns = @JoinColumn(name = "project_id"))

private Set<Project> projects;

10. @JoinColumn: Specifies the column used for joining in relationships.

@JoinColumn(name = "department_id")

@JoinTable: Defines a join table for many-to-many relationships.

@JoinTable(name = "employee_project",

joinColumns = @JoinColumn(name = "employee_id"),

inverseJoinColumns = @JoinColumn(name = "project_id"))

Hibernate Inheritance Mapping

Table Per Hierarchy

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.

Key Concepts of Table Per Hierarchy (TPH)

1. Single Table Mapping:

o Definition: All classes in the inheritance hierarchy are mapped to a


single table in the database.

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:

o Definition: A special column in the table used to determine which


subclass a particular row represents.

o Purpose: Helps the ORM framework decide how to instantiate the


correct subclass when querying the table.

3. Schema Representation:

o The table will have columns for all the properties of the base class and
all subclasses.

o It includes a discriminator column which holds a value indicating the


type of each record (e.g., FULL_TIME for full-time employees and
PART_TIME for part-time employees).
4. Inheritance Mapping:

o Base Class: The base class is mapped to the table and includes
common attributes.

o Subclasses: Each subclass has a discriminator value associated with


it. The subclass-specific attributes are also stored in the same table but
will be null for rows representing different subclass types.

Advantages of Table Per Hierarchy

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.

2. Performance: May offer performance benefits in terms of join operations


and querying, as all data resides in a single table.

3. Schema Evolution: Changes to the hierarchy structure (e.g., adding new


subclasses) may require fewer changes to the database schema.

Disadvantages of Table Per Hierarchy

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.

3. Complex Queries: Queries can become more complex as they need to


include conditions on the discriminator column to filter records of specific
types.
Example –

1. Define the Base Entity Class

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")

public abstract class Employee {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;


private String name;

// Default constructor

public Employee() {}

// Parameterized constructor

public Employee(String name) {

this.name = name;

// Getters and Setters

public Long getId() {

return id;

public void setId(Long id) {

this.id = id;

public String getName() {

return name;

}
public void setName(String name) {

this.name = name;

2. Define Subclass Entities with Constructors

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")

public class FullTimeEmployee extends Employee {

private double salary;

// Default constructor

public FullTimeEmployee() {

super();

// Parameterized constructor
public FullTimeEmployee(String name, double salary) {

super(name);

this.salary = salary;

// Getters and Setters

public double getSalary() {

return salary;

public void setSalary(double salary) {

this.salary = salary;

import javax.persistence.*;

@Entity

@DiscriminatorValue("PART_TIME")

public class PartTimeEmployee extends Employee {

private double hourlyRate;

// Default constructor
public PartTimeEmployee() {

super();

// Parameterized constructor

public PartTimeEmployee(String name, double hourlyRate) {

super(name);

this.hourlyRate = hourlyRate;

// Getters and Setters

public double getHourlyRate() {

return hourlyRate;

public void setHourlyRate(double 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>

<!-- Database connection settings -->

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

<!-- Specify dialect -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

<!-- Enable Hibernate's automatic session context management -->

<property
name="hibernate.current_session_context_class">thread</property>

<!-- Echo all executed SQL to stdout -->

<property name="hibernate.show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->

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

4. Using the Entities

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;

public class Main {

public static void main(String[] args) {

// Create SessionFactory

SessionFactory sessionFactory = new


Configuration().configure().buildSessionFactory();

// Open a new session

Session session = sessionFactory.openSession();

// Begin transaction
session.beginTransaction();

// Create and save FullTimeEmployee

FullTimeEmployee fullTimeEmployee = new FullTimeEmployee("John


Doe", 70000.00);

session.save(fullTimeEmployee);

// Create and save PartTimeEmployee

PartTimeEmployee partTimeEmployee = new PartTimeEmployee("Jane


Doe", 25.00);

session.save(partTimeEmployee);

// Commit transaction

session.getTransaction().commit();

// Close session and sessionFactory

session.close();

sessionFactory.close();

}
Example –

import javax.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class FirstInheritance {


public static void main(String[] args) {
testEmp();
}
static void testEmp() {
try {
System.out.println("Start Program");
Configuration configuration = new Configuration();
SessionFactory sessionFactory =
configuration.configure("hibernate.cfg.xml").buildSessionFac
tory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Emp e1 = new Emp(1, "AAA");
PEmp p1 = new PEmp(2,"BBB",125.1111);
CEmp c1 = new CEmp(3, "CCC", 1456.23);
session.merge(e1);
session.merge(p1);
session.merge(c1);
transaction.commit();
session.close();
System.out.println("Program End..");
}catch (Exception e) {
// TODO: handle exception
}
}
}

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

public PEmp(int id, String sname, double bonus) {


super(id, sname);
this.bonus = bonus;
}
public PEmp() {
}

@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(int id, String sname, double salary) {


super(id, sname);
this.salary = salary;
}

public CEmp() {

Table per Subclass

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.

In a table per subclass strategy (Using annotations)

The discriminator is optional so we can avoid discriminator-related annotations.

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

// Java Program to Illustrate Implementation of

// Employee Class

package com.exploit.org;

// Importing required classes

import javax.persistence.*;
// Annotations

@Entity

@Table(name = "employee")

@Inheritance(strategy = InheritanceType.JOINED)

// Class

public class Employee {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

@Column(name = "ID")

private String id;

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

B: File: R_Employee.java, which is implementing above class “Employee”

Example:

// Java Program to Illustrate Implementation of

// R_Employee Class
package com.exploit.org;

// Importing required classes

import javax.persistence.*;

// Annotations

@Entity

@Table(name = "r_employee")

@PrimaryKeyJoinColumn(name = "ID")

// Class

// Extending Employee class

public class R_Employee extends Employee {

@Column(name = "salary") private double salary;

@Column(name = "bonus") private double bonus;

C: File: C_Employee.java, which is implementing above class “Employee”

 Java

// Java Program to Illustrate Implementation of

// C_Employee Class
package com.exploit.org;

// Importing required classes

import javax.persistence.*;

// Annotations

@Entity

@Table(name = "c_employee")

@PrimaryKeyJoinColumn(name = "ID")

// Class

// Extending Employee class

public class C_Employee extends Employee {

@Column(name = "pay") private double pay;

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

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.*;

public class InheritanceSecondType {


public static void main(String[] args) {
Configuration cfg = new Configuration();
SessionFactory
sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
Session se=sf.openSession();
Transaction tr=se.beginTransaction();
SEMP s1= new SEMP(1, "AAA");
SPEmp s2 = new SPEmp(2, "BBB", 2500.65);
SCEmp s3 = new SCEmp(3, "CCC", 2600.56);
se.merge(s1);
se.merge(s2);
se.merge(s3);
tr.commit();
se.close();
}
}
@Entity
@Table(name="Second_Employee_1")
@Inheritance(strategy = InheritanceType.JOINED)
class SEMP{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;

@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(int id, String ename, double bonus) {


super(id, ename);
this.bonus = bonus;
}

public SPEmp() {
super();
}
}
@Entity
@Table(name="Second_Contract_Employee_1")
class SCEmp extends SEMP{
@Column(name="Second_contract_salary")
double salary;

public SCEmp(int id, String ename, double salary) {


super(id, ename);
this.salary = salary;
}

public SCEmp() {
super();
}
}

Table per Concrete class (using Annotations)


Table per Concrete Class is one of the inheritance strategies in hibernate. If we
want to keep each concrete class object of inheritance in separate tables of the
database then we can proceed with the table per concrete class strategy.

In a Table per Concrete Class strategy:

 Hibernate stores each derived class object of hierarchy in a separate table of


the database.

 Data that belongs to a parent class is scattered across a number of subclass


tables, which represent concrete classes.

 The discriminator is not required, so we can avoid discriminator-related


annotations.

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(int id, String ename, double bonus) {


super(id, ename);
this.bonus = bonus;
}

public TSPEmp() {
super();
}

@Entity
@Table(name="Third_Contract_Employee_1")
class TSCEmp extends TSEMP{
@Column(name="third_contract_salary")
double salary;

public TSCEmp(int id, String ename, double salary)


{
super(id, ename);
this.salary = 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.

the relationship that can be established between entities are-

 one to one — it represents the one to one relationship between two tables.

 one to many/many to one — it represents the one to many relationship


between two tables.

 many to many — it represents the many to many relationship between two


tables.

you all must have heard about these relationships. in this article, you will learn
about all relationships using hibernate.

one to many/many to one

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).

a. Example of one to many is One person have multiple bank account.


b. In this type we need to create a list because it has multiple objects but
in the one to one we create single object.
c. In the list we need to give the object those have multiple values.

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.

And use the lists other properties.

Example –

import java.util.*;

import javax.persistence.*;

import org.hibernate.*;

import org.hibernate.cfg.*;

public class OneToManyDemo {

public static void main(String[] args) {

Configuration cfg = new Configuration();

SessionFactory
sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
Session s=sf.openSession();

Transaction tr=s.beginTransaction();

Subject s1 = new Subject(1, "Computer");

Subject s2 = new Subject(2, "History");

Subject s3 = new Subject(3, "Maths");

Subject s4 = new Subject(4, "marathi");

List<Subject> l1 = new ArrayList<Subject>();

l1.add(s1);

l1.add(s2);

List<Subject> l2 = new ArrayList<Subject>();

l2.add(s3);

l2.add(s4);

Student ss1 = new Student(1, "AAA", l1);

Student ss2 = new Student(2, "BBB", l2);

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;

public Subject(int id, 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 ;

public Student(int id, String name, List<Subject> l1) {

super();

this.id = id;

this.name = name;

this.l1 = l1;

public Student() {

super();

}
One to Many using set

1. Using set we can’t store the duplicate objects.


2. We can’t maintain sequence order
3. And you can apply multiple features of set.

Example –

import java.util.*;

import javax.persistence.*;

import org.hibernate.*;

import org.hibernate.cfg.*;

public class OneToManyDemo {

public static void main(String[] args) {

Configuration cfg = new Configuration();


SessionFactory
sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();

Session s=sf.openSession();

Transaction tr=s.beginTransaction();

Subject s1 = new Subject(1, "Computer");

Subject s2 = new Subject(2, "History");

Subject s3 = new Subject(3, "Maths");

Subject s4 = new Subject(4, "marathi");

Set<Subject> l1 = new HashSet<Subject>();

l1.add(s1);

l1.add(s2);

Set<Subject> l2 = new Hashset<Subject>();

l2.add(s3);

l2.add(s4);

Student ss1 = new Student(1, "AAA", l1);

Student ss2 = new Student(2, "BBB", l2);

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;

public Subject(int id, 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 ;

public Student(int id, String name, 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.

Notice that bag is not index-based whereas list is index-based.

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.

You can use example of One to many by List.


One to many By Map

import javax.persistence.*;

import java.util.HashMap;

import java.util.Map;

@Entity

public class Department {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

@OneToMany(mappedBy = "department", cascade = CascadeType.ALL,


orphanRemoval = true)

@MapKey(name = "employeeId") // Key in the map is the employeeId of the


Employee entity

private Map<String, Employee> employees = new HashMap<>();

// Constructors, getters, and setters

public Department() {}
public Department(String name) {

this.name = name;

import javax.persistence.*;

@Entity

public class Employee {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(unique = true)

private String employeeId; // Unique identifier for the employee

private String name;

@ManyToOne

@JoinColumn(name = "department_id")

private Department department;


// Constructors, getters, and setters

public Employee() {}

public Employee(String employeeId, String name) {

this.employeeId = employeeId;

this.name = name;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

public class Main {

public static void main(String[] args) {

// Create a new Hibernate session factory

SessionFactory sessionFactory = new


Configuration().configure().buildSessionFactory();

// Create a new session

Session session = sessionFactory.openSession();

Transaction transaction = session.beginTransaction();


// Create department and employees

Department department = new Department("Human Resources");

Employee emp1 = new Employee("E001", "Alice");

Employee emp2 = new Employee("E002", "Bob");

// Add employees to department

department.addEmployee(emp1);

department.addEmployee(emp2);

// Save department (which will cascade to employees)

session.save(department);

transaction.commit();

session.close();

session.close();

sessionFactory.close();

You might also like