Hibernate Tutorial
Hibernate Tutorial
Hibernate Framework
ORM Tool
The ORM tool internally uses the JDBC API to interact with the
database.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides
certain functionality and standard to ORM tools.
The javax.persistence package contains the JPA classes and
interfaces.
2) Fast Performance
Hibernate Architecture
1. Hibernate Architecture
2. Elements of Hibernate Architecture
1. SessionFactory
2. Session
3. Transaction
4. ConnectionProvider
5. TransactionFactory
SessionFactory
Session
Transaction
ConnectionProvider
TransactionFactory
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp
1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-
5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialec
t</property>
<property name="connection.url">jdbc:oracle:thin:@localhost
:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.
OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry
;
9. import org.hibernate.boot.registry.StandardServiceRegistry
Builder;
10.
11.
public class StoreData {
public static void main(String[] args) {
//Create typesafe ServiceRegistry object
StandardServiceRegistry ssr = new StandardServiceRegistryBuil
der().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder(
).build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Employee e1=new Employee();
e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
5) Load the jar file
Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String firstName,lastName;
6.
7. public int getId() {
8. return id;
9. }
10. public void setId(int id) {
11. this.id = id;
12. }
13. public String getFirstName() {
14. return firstName;
15. }
16. public void setFirstName(String firstName) {
17. this.firstName = firstName;
18. }
19. public String getLastName() {
20. return lastName;
21. }
22. public void setLastName(String lastName) {
23. this.lastName = lastName;
24. }
25. }
employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-
5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.mypackage.Employee" tabl
e="emp1000">
8. <id name="id">
9. <generator class="assigned"></generator>
10. </id>
11.
12. <property name="firstName"></property>
13. <property name="lastName"></property>
14.
15. </class>
16.
17. </hibernate-mapping>
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-
configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracl
e9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@l
ocalhost:1521:xe</property>
12. <property name="connection.username">system</pr
operty>
13. <property name="connection.password">oracle</prop
erty>
14. <property name="connection.driver_class">oracle.jdb
c.driver.OracleDriver</property>
15. <mapping resource="employee.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry
;
9. import org.hibernate.boot.registry.StandardServiceRegistry
Builder;
10.
11. public class StoreData {
12.
13. public static void main( String[] args )
14. {
15. StandardServiceRegistry ssr = new StandardServiceR
egistryBuilder().configure("hibernate.cfg.xml").build();
16. Metadata meta = new MetadataSources(ssr).getMe
tadataBuilder().build();
17.
18. SessionFactory factory = meta.getSessionFactoryBuild
er().build();
19. Session session = factory.openSession();
20. Transaction t = session.beginTransaction();
21.
22. Employee e1=new Employee();
23. e1.setId(1);
24. e1.setFirstName("Gaurav");
25. e1.setLastName("Chawla");
26.
27. session.save(e1);
28. t.commit();
29. System.out.println("successfully saved");
30. factory.close();
31. session.close();
32. }
33. }
1. <mapping resource="employee.hbm.xml"/>
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4. "http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracl
e9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@l
ocalhost:1521:xe</property>
12. <property name="connection.username">system</pr
operty>
13. <property name="connection.password">oracle</prop
erty>
14. <property name="connection.driver_class">oracle.jdb
c.driver.OracleDriver</property>
15. <mapping resource="employee.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.cfg.Configuration;
7.
8. public class StoreData {
9. public static void main(String[] args) {
10.
11. //creating configuration object
12. Configuration cfg=new Configuration();
13. cfg.configure("hibernate.cfg.xml");//populates the data of
the configuration file
14.
15. //creating seession factory object
16. SessionFactory factory=cfg.buildSessionFactory();
17.
18. //creating session object
19. Session session=factory.openSession();
20.
21. //creating transaction object
22. Transaction t=session.beginTransaction();
23.
24. Employee e1=new Employee();
25. e1.setId(115);
26. e1.setFirstName("sonoo");
27. e1.setLastName("jaiswal");
28.
29. session.persist(e1);//persisting the object
30.
31. t.commit();//transaction is commited
32. session.close();
33.
34. System.out.println("successfully saved");
35.
36. }
37. }
Open pom.xml file and click source. Now, add the below
dependencies between <dependencies>....</dependencies>
tag. These dependencies are used to add the jar files in Maven
project.
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
6.
7. <dependency>
8. <groupId>com.oracle</groupId>
9. <artifactId>ojdbc14</artifactId>
10. <version>10.2.0.4.0</version>
11. </dependency>
o Install Maven
o Run the command : install-file
-Dfile=Path/to/your/ojdbc14.jar -DgroupId=com.oracle
-DartifactId=ojdbc14 -Dversion=12.1.0 -Dpackaging=jar
Employee.java
package com.javatpoint.mypackage;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name= "emp500")
public class Employee {
@Id
private int id;
private String firstName,lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-
5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dial
ect</property>
<property name="connection.url">jdbc:oracle:thin:@localho
st:1521:xe</property>
<property name="connection.username">system</property
>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.drive
r.OracleDriver</property>
<mapping class="com.javatpoint.mypackage.Employee"/>
</session-factory>
</hibernate-configuration>
StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.regis
try.StandardServiceRegistryBuilder;
public class StoreData {
public static void main(String[] args) {
StandardServiceRegistry ssr = new StandardServiceRegistryBui
lder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuild
er().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Employee e1=new Employee();
e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
index.jsp
This page gets input from the user and sends it to the register.jsp
file using post method.
1. <form action="register.jsp" method="post">
2. Name:<input type="text" name="name"/><br><br/>
3. Password:<input type="password" name="password"/><br
><br/>
4. Email ID:<input type="text" name="email"/><br><br/>
5. <input type="submit" value="register"/>"
6.
7. </form>
register.jsp
This file gets all request parameters and stores this information
into an object of User class. Further, it calls the register method
of UserDao class passing the User class object.
<%@page import="com.javatpoint.mypack.UserDao"%>
<jsp:useBean id="obj" class="com.javatpoint.mypack.User">
</jsp:useBean>
<jsp:setProperty property="*" name="obj"/>
<%
int i=UserDao.register(obj);
if(i>0)
out.print("You are successfully registered");
%>
User.java
package com.javatpoint.mypack;
public class User {
private int id;
private String name,password,email;
//getters and setters
}
user.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypack.User" table="u400">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="password"></property>
<property name="email"></property>
</class>
</hibernate-mapping>
UserDao.java
A Dao class, containing method to store the instance of User
class.
package com.javatpoint.mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class UserDao {
public static int register(User u){
int i=0;
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder
().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().
build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-
5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">create</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</pr
operty>
<property name="connection.url">jdbc:oracle:thin:@localhost:152
1:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.Oracl
eDriver</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Output
1. Hibernate Architecture
2. Hibernate Framework
3. Advantages of Hibernate Framework
1. assigned
2. increment
3. sequence
4. hilo
5. native
6. identity
7. seqhilo
8. uuid
9. guid
10. select
11. foreign
12. sequence-identity
1) assigned
1. ....
2. <hibernate-mapping>
3. <class ...>
4. <id ...>
5. <generator class="assigned"></generator>
6. </id>
7.
8. .....
9.
10. </class>
11. </hibernate-mapping>
2) increment
1. ....
2. <hibernate-mapping>
3. <class ...>
4. <id ...>
5. <generator class="increment"></generator>
6. </id>
7.
8. .....
9.
10. </class>
11. </hibernate-mapping>
3) sequence
1. .....
2. <id ...>
3. <generator class="sequence"></generator>
4. </id>
5. .....
For defining your own sequence, use the param subelement of
generator.
1. .....
2. <id ...>
3. <generator class="sequence">
4. <param name="sequence">your_sequence_name</par
am>
5. </generator>
6. </id>
7. .....
4) hilo
It uses high and low algorithm to generate the id of type short, int
and long. Syntax:
1. .....
2. <id ...>
3. <generator class="hilo"></generator>
4. </id>
5. .....
5) native
1. .....
2. <id ...>
3. <generator class="native"></generator>
4. </id>
5. .....
6) identity
It is used in Sybase, My SQL, MS SQL Server, DB2 and
HypersonicSQL to support the id column. The returned id is of
type short, int or long. It is responsibility of database to generate
unique identifier.
7) seqhilo
8) uuid
9) guid
10) select
11) foreign
1. <property name="dialect">org.hibernate.dialect.Oracle9Dial
ect</property>
RDBMS Dialect
Oracle9i org.hibernate.dialect.Oracle9iDialect
Oracle10g org.hibernate.dialect.Oracle10gDialect
MySQL org.hibernate.dialect.MySQLDialect
DB2 org.hibernate.dialect.DB2Dialect
Sybase org.hibernate.dialect.SybaseDialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Informix org.hibernate.dialect.InformixDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Ingres org.hibernate.dialect.IngresDialect
Progress org.hibernate.dialect.ProgressDialect
Interbase org.hibernate.dialect.
InterbaseDialect
Pointbase org.hibernate.dialect.
PointbaseDialect
FrontBase org.hibernate.dialect.
FrontbaseDialect
Firebird org.hibernate.dialect.
FirebirdDialect
1. Hibernate Logging
2. Example of Hibernate Logging
Logging enables the programmer to write the log details into a file
permanently. Log4j and Logback frameworks can be used in
hibernate framework to support logging.
Levels Description
There are two ways to perform logging using log4j using xml file:
You need to load the slf4j.jar and log4j.jar files with hibernate jar
files.
Now you need to create log4j.xml file. In this example, all the log
details will be written in the C:/javatpointlog.log file.
log4j.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
3. <log4j:configuration xmlns:log4j="http://jakarta.apache.org
/log4j/"
4. debug="false">
5. <appender name="CONSOLE" class="org.apache.log4j.Cons
oleAppender">
6. <layout class="org.apache.log4j.PatternLayout">
7. <param name="ConversionPattern" value="[%d{dd/MM/yy
hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
8. </layout>
9. </appender>
10. <appender name="ASYNC" class="org.apache.log4j.Asyn
cAppender">
11. <appender-ref ref="CONSOLE" />
12. <appender-ref ref="FILE" />
13. </appender>
14. <appender name="FILE" class="org.apache.log4j.RollingFile
Appender">
15. <param name="File" value="C:/javatpointlog.log" />
16. <param name="MaxBackupIndex" value="100" />
17. <layout class="org.apache.log4j.PatternLayout">
18. <param name="ConversionPattern" value="[%d{dd/MM/yy
hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
19. </layout>
20. </appender>
21. <category name="org.hibernate">
22. <priority value="DEBUG" />
23. </category>
24. <category name="java.sql">
25. <priority value="debug" />
26. </category>
27. <root>
28. <priority value="INFO" />
29. <appender-ref ref="FILE" />
30. </root>
31. </log4j:configuration>
1. Hibernate Logging
2. Example of Hibernate Logging
You need to load the slf4j.jar and log4j.jar files with hibernate jar
files.
log4j.properties
1. # Direct log messages to a log file
2. log4j.appender.file=org.apache.log4j.RollingFileAppender
3. log4j.appender.file.File=C:\\javatpointhibernate.log
4. log4j.appender.file.MaxFileSize=1MB
5. log4j.appender.file.MaxBackupIndex=1
6. log4j.appender.file.layout=org.apache.log4j.PatternLayout
7. log4j.appender.file.layout.ConversionPattern=
%d{ABSOLUTE} %5p %c{1}:%L - %m%n
8.
9. # Direct log messages to stdout
10. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
11. log4j.appender.stdout.Target=System.out
12. log4j.appender.stdout.layout=org.apache.log4j.PatternLayou
t
13. log4j.appender.stdout.layout.ConversionPattern=
%d{ABSOLUTE} %5p %c{1}:%L - %m%n
14.
15. # Root logger option
16. log4j.rootLogger=INFO, file, stdout
17.
18. # Log everything. Good for troubleshooting
19. log4j.logger.org.hibernate=INFO
20.
21. # Log all JDBC parameters
22. log4j.logger.org.hibernate.type=ALL
We can map the inheritance hierarchy classes with the table of the database. There are
three inheritance mapping strategies defined in the hibernate:
In table per hierarchy mapping, single table is required to map the whole hierarchy, an
extra column (known as discriminator column) is added to identify the class. But nullable
values are stored in the table .
In case of table per concrete class, tables are created as per class. But duplicate column is
added in subclass tables.
In this strategy, tables are created as per class but related by foreign key. So there are no
duplicate columns.
Let's understand the problem first. I want to map the whole hierarchy given below into one
table of the database.
There are three classes in this hierarchy. Employee is the super class for Regular_Employee
and Contract_Employee classes. Let's see the mapping file for this hierarchy.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator
-value="emp">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11.
12. <discriminator column="type" type="string"></discriminator>
13. <property name="name"></property>
14.
15. <subclass name="com.javatpoint.mypackage.Regular_Employee" discriminator-
value="reg_emp">
16. <property name="salary"></property>
17. <property name="bonus"></property>
18. </subclass>
19.
20. <subclass name="com.javatpoint.mypackage.Contract_Employee" discriminator-
value="con_emp">
21. <property name="pay_per_hour"></property>
22. <property name="contract_duration"></property>
23. </subclass>
24.
25. </class>
26.
27. </hibernate-mapping>
In case of table per class hierarchy an discriminator column is added by the hibernate
framework that specifies the type of the record. It is mainly used to distinguish the
record. To specify this, discriminator subelement of class must be specified.
You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. //getters and setters
8. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Regular_Employee extends Employee{
4. private float salary;
5. private int bonus;
6.
7. //getters and setters
8. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Contract_Employee extends Employee{
4. private float pay_per_hour;
5. private String contract_duration;
6.
7. //getters and setters
8. }
File: employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator
-value="emp">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11.
12. <discriminator column="type" type="string"></discriminator>
13. <property name="name"></property>
14.
15. <subclass name="com.javatpoint.mypackage.Regular_Employee" discriminator-
value="reg_emp">
16. <property name="salary"></property>
17. <property name="bonus"></property>
18. </subclass>
19.
20. <subclass name="com.javatpoint.mypackage.Contract_Employee" discriminator-
value="con_emp">
21. <property name="pay_per_hour"></property>
22. <property name="contract_duration"></property>
23. </subclass>
24.
25. </class>
26.
27. </hibernate-mapping>
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
1. <mapping resource="employee.hbm.xml"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="employee.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2. import org.hibernate.Session;
3. import org.hibernate.SessionFactory;
4. import org.hibernate.Transaction;
5. import org.hibernate.boot.Metadata;
6. import org.hibernate.boot.MetadataSources;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9.
10. public class StoreData {
11. public static void main(String[] args) {
12.
13. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
14. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
15.
16. SessionFactory factory=meta.getSessionFactoryBuilder().build();
17. Session session=factory.openSession();
18.
19. Transaction t=session.beginTransaction();
20.
21. Employee e1=new Employee();
22. e1.setName("Gaurav Chawla");
23.
24. Regular_Employee e2=new Regular_Employee();
25. e2.setName("Vivek Kumar");
26. e2.setSalary(50000);
27. e2.setBonus(5);
28.
29. Contract_Employee e3=new Contract_Employee();
30. e3.setName("Arjun Kumar");
31. e3.setPay_per_hour(1000);
32. e3.setContract_duration("15 hours");
33.
34. session.persist(e1);
35. session.persist(e2);
36. session.persist(e3);
37.
38. t.commit();
39. session.close();
40. System.out.println("success");
41. }
42. }
Output:
Hibernate Table Per Hierarchy using Annotation
1. Table Per Hierarchy
2. Example of Table Per Hierarchy
In the previous page, we have mapped the inheritance hierarchy with one table using xml
file. Here, we are going to perform this task using annotation. You need to use
@Inheritance(strategy=InheritanceType.SINGLE_TABLE), @DiscriminatorColumn and
@DiscriminatorValue annotations for mapping table per hierarchy strategy.
In case of table per hierarchy, only one table is required to map the inheritance hierarchy.
Here, an extra column (also known as discriminator column) is created in the table to
identify the class.
There are three classes in this hierarchy. Employee is the super class for Regular_Employee
and Contract_Employee classes.
The table structure for this hierarchy is as shown below:
You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:
File: Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee101")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
//setters and getters
}
File: Regular_Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
//setters and getters
}
File: Contract_Employee.java
package com.javatpoint.mypackage;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("contractemployee")
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
//setters and getters
}
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
6.
7. <dependency>
8. <groupId>com.oracle</groupId>
9. <artifactId>ojdbc14</artifactId>
10. <version>10.2.0.4.0</version>
11. </dependency>
Open the hibernate.cgf.xml file, and add entries of entity classes like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreTest.java
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class StoreTest {
public static void main(String args[])
{
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernat
e.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Employee e1=new Employee();
e1.setName("Gaurav Chawla");
Regular_Employee e2=new Regular_Employee();
e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3=new Contract_Employee();
e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Output:
In case of Table Per Concrete class, there will be three tables in the database having no
relations to each other. There are two ways to map the table with table per concrete class
strategy.
o By union-subclass element
o By self creating the table for each class
Let's understand what hierarchy we are going to map.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.mypackage.Employee" table="emp122">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11.
12. <property name="name"></property>
13.
14. <union-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp122">
15. <property name="salary"></property>
16. <property name="bonus"></property>
17. </union-subclass>
18.
19. <union-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp122">
20. <property name="pay_per_hour"></property>
21. <property name="contract_duration"></property>
22. </union-subclass>
23.
24. </class>
25.
26. </hibernate-mapping>
In case of table per concrete class, there will be three tables in the database, each
representing a particular class.
Table structure for Contract_Employee class
You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. //getters and setters
8. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Regular_Employee extends Employee{
4. private float salary;
5. private int bonus;
6.
7. //getters and setters
8. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Contract_Employee extends Employee{
4. private float pay_per_hour;
5. private String contract_duration;
6.
7. //getters and setters
8. }
File: employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6.
7. <hibernate-mapping>
8. <class name="com.javatpoint.mypackage.Employee" table="emp122">
9. <id name="id">
10. <generator class="increment"></generator>
11. </id>
12.
13. <property name="name"></property>
14.
15. <union-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp122">
16. <property name="salary"></property>
17. <property name="bonus"></property>
18. </union-subclass>
19.
20. <union-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp122">
21. <property name="pay_per_hour"></property>
22. <property name="contract_duration"></property>
23. </union-subclass>
24.
25. </class>
26.
27. </hibernate-mapping>
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
1. <mapping resource="employee.hbm.xml"/>
File: hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="employee.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class StoreData {
12.
13. public static void main(String[] args) {
14.
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. Transaction t=session.beginTransaction();
22.
23. Employee e1=new Employee();
24. e1.setName("Gaurav Chawla");
25.
26. Regular_Employee e2=new Regular_Employee();
27. e2.setName("Vivek Kumar");
28. e2.setSalary(50000);
29. e2.setBonus(5);
30.
31. Contract_Employee e3=new Contract_Employee();
32. e3.setName("Arjun Kumar");
33. e3.setPay_per_hour(1000);
34. e3.setContract_duration("15 hours");
35.
36. session.persist(e1);
37. session.persist(e2);
38. session.persist(e3);
39.
40. t.commit();
41. session.close();
42. System.out.println("success");
43. }
44. }
In case of Table Per Concrete class, tables are created per class. So there are no nullable
values in the table. Disadvantage of this approach is that duplicate columns are created in
the subclass tables.
Table structure for Contract_Employee class
You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name = "employee102")
6. @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
7.
8. public class Employee {
9. @Id
10. @GeneratedValue(strategy=GenerationType.AUTO)
11.
12. @Column(name = "id")
13. private int id;
14.
15. @Column(name = "name")
16. private String name;
17.
18. //setters and getters
19. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name="regularemployee102")
6. @AttributeOverrides({
7. @AttributeOverride(name="id", column=@Column(name="id")),
8. @AttributeOverride(name="name", column=@Column(name="name"))
9. })
10. public class Regular_Employee extends Employee{
11.
12. @Column(name="salary")
13. private float salary;
14.
15. @Column(name="bonus")
16. private int bonus;
17.
18. //setters and getters
19. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3. @Entity
4. @Table(name="contractemployee102")
5. @AttributeOverrides({
6. @AttributeOverride(name="id", column=@Column(name="id")),
7. @AttributeOverride(name="name", column=@Column(name="name"))
8. })
9. public class Contract_Employee extends Employee{
10.
11. @Column(name="pay_per_hour")
12. private float pay_per_hour;
13.
14. @Column(name="contract_duration")
15. private String contract_duration;
16.
17. public float getPay_per_hour() {
18. return pay_per_hour;
19. }
20. public void setPay_per_hour(float payPerHour) {
21. pay_per_hour = payPerHour;
22. }
23. public String getContract_duration() {
24. return contract_duration;
25. }
26. public void setContract_duration(String contractDuration) {
27. contract_duration = contractDuration;
28. }
29. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
6.
7. <dependency>
8. <groupId>com.oracle</groupId>
9. <artifactId>ojdbc14</artifactId>
10. <version>10.2.0.4.0</version>
11. </dependency>
File: hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <!-- Generated by MyEclipse Hibernate Tools. -->
7. <hibernate-configuration>
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
15.
16. <mapping class="com.javatpoint.mypackage.Employee"/>
17. <mapping class="com.javatpoint.mypackage.Contract_Employee"/>
18. <mapping class="com.javatpoint.mypackage.Regular_Employee"/>
19. </session-factory>
20. </hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class StoreData {
12.
13. public static void main(String[] args) {
14.
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure(
"hibernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. Transaction t=session.beginTransaction();
22.
23. Employee e1=new Employee();
24. e1.setName("Gaurav Chawla");
25.
26. Regular_Employee e2=new Regular_Employee();
27. e2.setName("Vivek Kumar");
28. e2.setSalary(50000);
29. e2.setBonus(5);
30.
31. Contract_Employee e3=new Contract_Employee();
32. e3.setName("Arjun Kumar");
33. e3.setPay_per_hour(1000);
34. e3.setContract_duration("15 hours");
35.
36. session.persist(e1);
37. session.persist(e2);
38. session.persist(e3);
39.
40. t.commit();
41. session.close();
42. System.out.println("success");
43. }
44. }
In case of Table Per Subclass, subclass mapped tables are related to parent class mapped
table by primary key and foreign key relationship.
The <joined-subclass> element of class is used to map the child class with parent using
the primary key and foreign key relation.
In this example, we are going to use hb2ddl.auto property to generate the table
automatically. So we don't need to be worried about creating tables in the database.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3.
4. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
5. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
6.
7.
8. <hibernate-mapping>
9. <class name="com.javatpoint.mypackage.Employee" table="emp123">
10. <id name="id">
11. <generator class="increment"></generator>
12. </id>
13.
14. <property name="name"></property>
15.
16. <joined-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp123">
17. <key column="eid"></key>
18. <property name="salary"></property>
19. <property name="bonus"></property>
20. </joined-subclass>
21.
22. <joined-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp123">
23. <key column="eid"></key>
24. <property name="pay_per_hour"></property>
25. <property name="contract_duration"></property>
26. </joined-subclass>
27.
28. </class>
29. </hibernate-mapping>
In case of table per subclass class, there will be three tables in the database, each
representing a particular class.
Table structure for Contract_Employee class
You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. //getters and setters
8. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2. public class Regular_Employee extends Employee{
3. private float salary;
4. private int bonus;
5.
6. //getters and setters
7. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Contract_Employee extends Employee{
4. private float pay_per_hour;
5. private String contract_duration;
6.
7. //getters and setters
8. }
File: employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3.
4. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
5. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
6.
7.
8. <hibernate-mapping>
9. <class name="com.javatpoint.mypackage.Employee" table="emp123">
10. <id name="id">
11. <generator class="increment"></generator>
12. </id>
13.
14. <property name="name"></property>
15.
16. <joined-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp123">
17. <key column="eid"></key>
18. <property name="salary"></property>
19. <property name="bonus"></property>
20. </joined-subclass>
21.
22. <joined-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp123">
23. <key column="eid"></key>
24. <property name="pay_per_hour"></property>
25. <property name="contract_duration"></property>
26. </joined-subclass>
27.
28. </class>
29. </hibernate-mapping>
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
1. <mapping resource="employee.hbm.xml"/>
File: hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="employee.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class StoreData {
12. public static void main(String[] args) {
13.
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hiber
nate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.buildSessionFactory();
18. Session session=factory.openSession();
19.
20. Transaction t=session.beginTransaction();
21.
22. Employee e1=new Employee();
23. e1.setName("Gaurav Chawla");
24.
25. Regular_Employee e2=new Regular_Employee();
26. e2.setName("Vivek Kumar");
27. e2.setSalary(50000);
28. e2.setBonus(5);
29.
30. Contract_Employee e3=new Contract_Employee();
31. e3.setName("Arjun Kumar");
32. e3.setPay_per_hour(1000);
33. e3.setContract_duration("15 hours");
34.
35. session.persist(e1);
36. session.persist(e2);
37. session.persist(e3);
38.
39. t.commit();
40. session.close();
41. System.out.println("success");
42.
43. }
44. }
As we have specified earlier, in case of table per subclass strategy, tables are created as per
persistent classes but they are treated using primary and foreign key. So there will not be
any duplicate column in the relation.
The table structure for each table will be as follows:
You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name = "employee103")
6. @Inheritance(strategy=InheritanceType.JOINED)
7.
8. public class Employee {
9. @Id
10. @GeneratedValue(strategy=GenerationType.AUTO)
11.
12. @Column(name = "id")
13. private int id;
14.
15. @Column(name = "name")
16. private String name;
17.
18. //setters and getters
19. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="regularemployee103")
7. @PrimaryKeyJoinColumn(name="ID")
8. public class Regular_Employee extends Employee{
9.
10. @Column(name="salary")
11. private float salary;
12.
13. @Column(name="bonus")
14. private int bonus;
15.
16. //setters and getters
17. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="contractemployee103")
7. @PrimaryKeyJoinColumn(name="ID")
8. public class Contract_Employee extends Employee{
9.
10. @Column(name="pay_per_hour")
11. private float pay_per_hour;
12.
13. @Column(name="contract_duration")
14. private String contract_duration;
15.
16. //setters and getters
17. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
6.
7. <dependency>
8. <groupId>com.oracle</groupId>
9. <artifactId>ojdbc14</artifactId>
10. <version>10.2.0.4.0</version>
11. </dependency>
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
1. <mapping class="com.javatpoint.mypackage.Employee"/>
2. <mapping class="com.javatpoint.mypackage.Contract_Employee"/>
3. <mapping class="com.javatpoint.mypackage.Regular_Employee"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <!-- Generated by MyEclipse Hibernate Tools. -->
7. <hibernate-configuration>
8.
9. <session-factory>
10. <property name="hbm2ddl.auto">update</property>
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
13. <property name="connection.username">system</property>
14. <property name="connection.password">jtp</property>
15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
16.
17. <mapping class="com.javatpoint.mypackage.Employee"/>
18. <mapping class="com.javatpoint.mypackage.Contract_Employee"/>
19. <mapping class="com.javatpoint.mypackage.Regular_Employee"/>
20. </session-factory>
21.
22. </hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class StoreData {
12.
13. public static void main(String args[])
14. {
15. StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure
("hibernate.cfg.xml").build();
16. Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. Transaction t=session.beginTransaction();
22.
23. Employee e1=new Employee();
24. e1.setName("Gaurav Chawla");
25.
26. Regular_Employee e2=new Regular_Employee();
27. e2.setName("Vivek Kumar");
28. e2.setSalary(50000);
29. e2.setBonus(5);
30.
31. Contract_Employee e3=new Contract_Employee();
32. e3.setName("Arjun Kumar");
33. e3.setPay_per_hour(1000);
34. e3.setContract_duration("15 hours");
35.
36. session.persist(e1);
37. session.persist(e2);
38. session.persist(e3);
39.
40. t.commit();
41. session.close();
42. System.out.println("success");
43. }
44. }
Collection Mapping in Hibernate
1. Collection Mapping in Hibernate
2. Mapping collection in mapping file
3. Understanding key element
4. Indexed collections
5. Collection Elements
We can map collection elements of Persistent class in Hibernate. You need to declare the
type of collection in Persistent class from one of the following types:
o java.util.List
o java.util.Set
o java.util.SortedSet
o java.util.Map
o java.util.SortedMap
o java.util.Collection
o or write the implementation of org.hibernate.usertype.UserCollectionType
The persistent class should be defined like this for collection element.
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private List<String> answers;//List can be of any type
9.
10. //getters and setters
11.
12. }
1. <class name="com.javatpoint.Question" table="q100">
2. <id name="id">
3. <generator class="increment"></generator>
4. </id>
5. <property name="qname"></property>
6.
7. <list name="answers" table="ans100">
8. <key column="qid"></key>
9. <index column="type"></index>
10. <element column="answer" type="string"></element>
11. </list>
12.
13. </class>
o <key> element is used to define the foreign key in this table based on the Question
class identifier.
o <index> element is used to identify the type. List and Map are indexed collection.
o <element> is used to define the element of the collection.
This is the mapping of collection if collection stores string objects. But if collection stores
entity reference (another class objects), we need to define <one-to-many> or <many-to-
many> element. Now the Persistent class will look like:
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private List<Answer> answers;//Here, List stores the objects of Answer class
9.
10. //getters and setters
11.
12. }
1. package com.javatpoint;
2. import java.util.List;
3. public class Answer {
4. private int id;
5. private String answer;
6. private String posterName;
7. //getters and setters
8. }
1. <class name="com.javatpoint.Question" table="q100">
2. <id name="id">
3. <generator class="increment"></generator>
4. </id>
5. <property name="qname"></property>
6.
7. <list name="answers" >
8. <key column="qid"></key>
9. <index column="type"></index>
10. <one-to-many class="com.javatpoint.Answer" />
11. </list>
12.
13. </class>
Here, List is mapped by one-to-many relation. In this scenario, there can be many answers
for one question.
1. <key column="qid" not-null="true" ></key>
The attributes of the key element are column, on-delete, property-ref, not-null, update and
unique.
1. <key
2. column="columnname"
3. on-delete="noaction|cascade"
4. not-null="true|false"
5. property-ref="propertyName"
6. update="true|false"
7. unique="true|false"
8. />
Indexed collections
The collection elements can be categorized in two forms:
o indexed ,and
o non-indexed
The List and Map collection are indexed whereas set and bag collections are non-indexed.
Here, indexed collection means List and Map requires an additional element <index>.
Collection Elements
The collection elements can have value or entity reference (another class object). We can
use one of the 4 elements
o element
o component-element
o one-to-many, or
o many-to-many
The element and component-element are used for normal value such as string, int etc.
whereas one-to-many and many-to-many are used to map entity reference.
Mapping Bag
In this example, we are going to use the bag collection of Hibernate framework.
Mapping Set
If our persistent class has List object, we can map the List easily either by <list> element of
class in mapping file or by annotation.
Here, we are using the scenario of Forum where one question has multiple answers.
Let's see how we can implement the list in the mapping file:
1. <class name="com.javatpoint.Question" table="q100">
2. ...
3. <list name="answers" table="ans100">
4. <key column="qid"></key>
5. <index column="type"></index>
6. <element column="answer" type="string"></element>
7. </list>
8.
9. ...
10. </class>
List and Map are index based collection, so an extra column will be created in the table for indexing.
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private List<String> answers;
9.
10. //getters and setters
11.
12. }
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Question" table="q100">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11. <property name="qname"></property>
12.
13. <list name="answers" table="ans100">
14. <key column="qid"></key>
15. <index column="type"></index>
16. <element column="answer" type="string"></element>
17. </list>
18.
19. </class>
20.
21. </hibernate-mapping>
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="question.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
1. package com.javatpoint;
2.
3. import java.util.ArrayList;
4.
5. import org.hibernate.*;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class StoreData {
12. public static void main(String[] args) {
13.
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. Transaction t=session.beginTransaction();
21.
22. ArrayList<String> list1=new ArrayList<String>();
23. list1.add("Java is a programming language");
24. list1.add("Java is a platform");
25.
26. ArrayList<String> list2=new ArrayList<String>();
27. list2.add("Servlet is an Interface");
28. list2.add("Servlet is an API");
29.
30. Question question1=new Question();
31. question1.setQname("What is Java?");
32. question1.setAnswers(list1);
33.
34. Question question2=new Question();
35. question2.setQname("What is Servlet?");
36. question2.setAnswers(list2);
37.
38. session.persist(question1);
39. session.persist(question2);
40.
41. t.commit();
42. session.close();
43. System.out.println("success");
44. }
45. }
Output
1. package com.javatpoint;
2.
3. import javax.persistence.TypedQuery;
4. import java.util.*;
5. import org.hibernate.*;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class FetchData {
12. public static void main(String[] args) {
13.
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. TypedQuery query=session.createQuery("from Question");
21. List<Question> list=query.getResultList();
22.
23. Iterator<Question> itr=list.iterator();
24. while(itr.hasNext()){
25. Question q=itr.next();
26. System.out.println("Question Name: "+q.getQname());
27.
28. //printing answers
29. List<String> list2=q.getAnswers();
30. Iterator<String> itr2=list2.iterator();
31. while(itr2.hasNext()){
32. System.out.println(itr2.next());
33. }
34. }
35. session.close();
36. System.out.println("success");
37. }
38. }
Output
If our persistent class has List object, we can map the List by list or bag element in the
mapping file. The bag is just like List but it doesn't require index element.
Here, we are using the scenario of Forum where one question has multiple answers.
Let's see how we can implement the bag in the mapping file:
1. <class name="com.javatpoint.Question" table="q100">
2. ...
3. <bag name="answers" table="ans100">
4. <key column="qid"></key>
5. <element column="answer" type="string"></element>
6. </bag>
7.
8. ...
9. </class>
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private List<String> answers;
9.
10. //getters and setters
11.
12. }
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Question" table="q101">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11. <property name="qname"></property>
12.
13. <bag name="answers" table="ans101">
14. <key column="qid"></key>
15. <element column="answer" type="string"></element>
16. </bag>
17.
18. </class>
19.
20. </hibernate-mapping>
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <!-- Generated by MyEclipse Hibernate Tools. -->
7. <hibernate-configuration>
8.
9. <session-factory>
10. <property name="hbm2ddl.auto">update</property>
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
13. <property name="connection.username">system</property>
14. <property name="connection.password">jtp</property>
15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
16. <mapping resource="question.hbm.xml"/>
17. </session-factory>
18.
19. </hibernate-configuration>
1. package com.javatpoint;
2.
3. import java.util.ArrayList;
4.
5. import org.hibernate.Session;
6. import org.hibernate.SessionFactory;
7. import org.hibernate.Transaction;
8. import org.hibernate.boot.Metadata;
9. import org.hibernate.boot.MetadataSources;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12.
13. public class StoreData {
14. public static void main(String[] args) {
15.
16. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
17. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
18.
19. SessionFactory factory=meta.buildSessionFactory();
20. Session session=factory.openSession();
21.
22. Transaction t=session.beginTransaction();
23.
24. ArrayList<String> list1=new ArrayList<String>();
25. list1.add("Java is a programming language");
26. list1.add("Java is a platform");
27.
28. ArrayList<String> list2=new ArrayList<String>();
29. list2.add("Servlet is an Interface");
30. list2.add("Servlet is an API");
31.
32. Question question1=new Question();
33. question1.setQname("What is Java?");
34. question1.setAnswers(list1);
35.
36. Question question2=new Question();
37. question2.setQname("What is Servlet?");
38. question2.setAnswers(list2);
39.
40. session.persist(question1);
41. session.persist(question2);
42.
43. t.commit();
44. session.close();
45. System.out.println("success");
46. }
47. }
Output
1. package com.javatpoint;
2.
3. import javax.persistence.TypedQuery;
4. import java.util.*;
5. import org.hibernate.*;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11.
12. public class FetchData {
13. public static void main(String[] args) {
14.
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.buildSessionFactory();
19. Session session=factory.openSession();
20.
21. TypedQuery query=session.createQuery("from Question");
22. List<Question> list=query.getResultList();
23.
24. Iterator<Question> itr=list.iterator();
25. while(itr.hasNext()){
26. Question q=itr.next();
27. System.out.println("Question Name: "+q.getQname());
28.
29. //printing answers
30. List<String> list2=q.getAnswers();
31. Iterator<String> itr2=list2.iterator();
32. while(itr2.hasNext()){
33. System.out.println(itr2.next());
34. }
35.
36. }
37. session.close();
38. System.out.println("success");
39.
40. }
41. }
Output
If our persistent class has Set object, we can map the Set by set element in the mapping
file. The set element doesn't require index element. The one difference between List and Set
is that, it stores only unique values.
Let's see how we can implement the set in the mapping file:
1. <class name="com.javatpoint.Question" table="q1002">
2. ...
3. <set name="answers" table="ans1002">
4. <key column="qid"></key>
5. <element column="answer" type="string"></element>
6. </set>
7.
8. ...
9. </class>
1. package com.javatpoint;
2.
3. import java.util.Set;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private Set<String> answers;
9.
10. //getters and setters
11.
12. }
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Question" table="q1002">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11. <property name="qname"></property>
12.
13. <set name="answers" table="ans1002">
14. <key column="qid"></key>
15. <element column="answer" type="string"></element>
16. </set>
17.
18. </class>
19.
20. </hibernate-mapping>
3) create the configuration file
This file contains information about the database and mapping file.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="question.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
1. package com.javatpoint;
2.
3. import java.util.HashSet;
4.
5. import org.hibernate.*;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class StoreData {
12. public static void main(String[] args) {
13.
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. Transaction t=session.beginTransaction();
21.
22.
23. HashSet<String> set1=new HashSet<String>();
24. set1.add("Java is a programming language");
25. set1.add("Java is a platform");
26.
27. HashSet<String> set2=new HashSet<String>();
28. set2.add("Servlet is an Interface");
29. set2.add("Servlet is an API");
30.
31. Question question1=new Question();
32. question1.setQname("What is Java?");
33. question1.setAnswers(set1);
34.
35. Question question2=new Question();
36. question2.setQname("What is Servlet?");
37. question2.setAnswers(set2);
38.
39. session.persist(question1);
40. session.persist(question2);
41.
42. t.commit();
43. session.close();
44. System.out.println("success");
45. }
46. }
Output
1. package com.javatpoint;
2.
3. import java.util.*;
4.
5. import javax.persistence.TypedQuery;
6.
7. import org.hibernate.*;
8. import org.hibernate.boot.Metadata;
9. import org.hibernate.boot.MetadataSources;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12.
13. public class FetchData {
14. public static void main(String[] args) {
15.
16. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
17. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
18.
19. SessionFactory factory=meta.getSessionFactoryBuilder().build();
20. Session session=factory.openSession();
21.
22. Transaction t=session.beginTransaction();
23.
24. TypedQuery query=session.createQuery("from Question");
25. List<Question> list=query.getResultList();
26.
27. Iterator<Question> itr=list.iterator();
28. while(itr.hasNext()){
29. Question q=itr.next();
30. System.out.println("Question Name: "+q.getQname());
31.
32. //printing answers
33. Set<String> set=q.getAnswers();
34. Iterator<String> itr2=set.iterator();
35. while(itr2.hasNext()){
36. System.out.println(itr2.next());
37. }
38.
39. }
40. session.close();
41. System.out.println("success");
42.
43. }
44. }
Output
Hibernate allows you to map Map elements with the RDBMS. As we know, list and map are
index-based collections. In case of map, index column works as the key and element
column works as the value.
o Question.java
o question.hbm.xml
o hibernate.cfg.xml
o StoreTest.java
o FetchTest.java
Question.java
1. package com.javatpoint;
2.
3. import java.util.Map;
4.
5. public class Question {
6. private int id;
7. private String name,username;
8. private Map<String,String> answers;
9.
10. public Question() {}
11. public Question(String name, String username, Map<String, String> answers) {
12. super();
13. this.name = name;
14. this.username = username;
15. this.answers = answers;
16. }
17. public int getId() {
18. return id;
19. }
20. public void setId(int id) {
21. this.id = id;
22. }
23. public String getName() {
24. return name;
25. }
26. public void setName(String name) {
27. this.name = name;
28. }
29. public String getUsername() {
30. return username;
31. }
32. public void setUsername(String username) {
33. this.username = username;
34. }
35. public Map<String, String> getAnswers() {
36. return answers;
37. }
38. public void setAnswers(Map<String, String> answers) {
39. this.answers = answers;
40. }
41. }
question.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7.
8. <class name="com.javatpoint.Question" table="question736">
9. <id name="id">
10. <generator class="native"></generator>
11. </id>
12. <property name="name"></property>
13. <property name="username"></property>
14.
15. <map name="answers" table="answer736" cascade="all">
16. <key column="questionid"></key>
17. <index column="answer" type="string"></index>
18. <element column="username" type="string"></element>
19. </map>
20. </class>
21.
22. </hibernate-mapping>
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15.
16. <mapping resource="question.hbm.xml"/>
17. </session-factory>
18.
19. </hibernate-configuration>
StoreTest.java
1. package com.javatpoint;
2.
3. import java.util.HashMap;
4. import org.hibernate.*;
5. import org.hibernate.boot.Metadata;
6. import org.hibernate.boot.MetadataSources;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9.
10.
11. public class StoreTest {
12. public static void main(String[] args) {
13.
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. Transaction t=session.beginTransaction();
21.
22. HashMap<String,String> map1=new HashMap<String,String>();
23. map1.put("Java is a programming language","John Milton");
24. map1.put("Java is a platform","Ashok Kumar");
25.
26. HashMap<String,String> map2=new HashMap<String,String>();
27. map2.put("Servlet technology is a server side programming","John Milton");
28. map2.put("Servlet is an Interface","Ashok Kumar");
29. map2.put("Servlet is a package","Rahul Kumar");
30.
31. Question question1=new Question("What is Java?","Alok",map1);
32. Question question2=new Question("What is Servlet?","Jai Dixit",map2);
33.
34. session.persist(question1);
35. session.persist(question2);
36.
37. t.commit();
38. session.close();
39. System.out.println("successfully stored");
40. }
41. }
Output
FetchTest.java
1. package com.javatpoint;
2. import java.util.*;
3.
4. import javax.persistence.TypedQuery;
5.
6. import org.hibernate.*;
7. import org.hibernate.boot.Metadata;
8. import org.hibernate.boot.MetadataSources;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11.
12. public class FetchTest {
13. public static void main(String[] args) {
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. TypedQuery query=session.createQuery("from Question ");
21. List<Question> list=query.getResultList();
22.
23. Iterator<Question> iterator=list.iterator();
24. while(iterator.hasNext()){
25. Question question=iterator.next();
26. System.out.println("question id:"+question.getId());
27. System.out.println("question name:"+question.getName());
28. System.out.println("question posted by:"+question.getUsername());
29. System.out.println("answers.....");
30. Map<String,String> map=question.getAnswers();
31. Set<Map.Entry<String,String>> set=map.entrySet();
32.
33. Iterator<Map.Entry<String,String>> iteratoranswer=set.iterator();
34. while(iteratoranswer.hasNext()){
35. Map.Entry<String,String> entry=(Map.Entry<String,String>)iteratoranswer.next()
;
36. System.out.println("answer name:"+entry.getKey());
37. System.out.println("answer posted by:"+entry.getValue());
38. }
39. }
40. session.close();
41. }
42. }
Output
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.
Here, we are using the scenario of Forum where one question has multiple answers.
In such case, there can be many answers for a question and each answer may have its own
informations that is why we have used list in the persistent class (containing the reference
of Answer class) to represent a collection of answers.
Let's see the persistent class that has list objects (containing Answer class objects).
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private List<Answer> answers;
9. //getters and setters
10.
11. }
The Answer class has its own informations such as id, answername, postedBy etc.
1. package com.javatpoint;
2.
3. public class Answer {
4. private int id;
5. private String answername;
6. private String postedBy;
7. //getters and setters
8.
9. }
10. }
The Question class has list object that have entity reference (i.e. Answer class object). In
such case, we need to use one-to-many of list to map this object. Let's see how we can
map it.
1. <list name="answers" cascade="all">
2. <key column="qid"></key>
3. <index column="type"></index>
4. <one-to-many class="com.javatpoint.Answer"/>
5. </list>
Question.java
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private List<Answer> answers;
9.
10. //getters and setters
11.
12. }
Answer.java
1. package com.javatpoint;
2.
3. public class Answer {
4. private int id;
5. private String answername;
6. private String postedBy;
7. //getters and setters
8.
9. }
10. }
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Question" table="q501">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11. <property name="qname"></property>
12.
13. <list name="answers" cascade="all">
14. <key column="qid"></key>
15. <index column="type"></index>
16. <one-to-many class="com.javatpoint.Answer"/>
17. </list>
18.
19. </class>
20.
21. <class name="com.javatpoint.Answer" table="ans501">
22. <id name="id">
23. <generator class="increment"></generator>
24. </id>
25. <property name="answername"></property>
26. <property name="postedBy"></property>
27. </class>
28.
29. </hibernate-mapping>
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <!-- Generated by MyEclipse Hibernate Tools. -->
7. <hibernate-configuration>
8.
9. <session-factory>
10. <property name="hbm2ddl.auto">update</property>
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
13. <property name="connection.username">system</property>
14. <property name="connection.password">jtp</property>
15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
16. <mapping resource="question.hbm.xml"/>
17. </session-factory>
18.
19. </hibernate-configuration>
1. package com.javatpoint;
2.
3. import java.util.ArrayList;
4. import org.hibernate.Session;
5. import org.hibernate.SessionFactory;
6. import org.hibernate.Transaction;
7. import org.hibernate.boot.Metadata;
8. import org.hibernate.boot.MetadataSources;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11. public class StoreData {
12. public static void main(String[] args) {
13.
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. Transaction t=session.beginTransaction();
21.
22. Answer ans1=new Answer();
23. ans1.setAnswername("Java is a programming language");
24. ans1.setPostedBy("Ravi Malik");
25.
26. Answer ans2=new Answer();
27. ans2.setAnswername("Java is a platform");
28. ans2.setPostedBy("Sudhir Kumar");
29.
30. Answer ans3=new Answer();
31. ans3.setAnswername("Servlet is an Interface");
32. ans3.setPostedBy("Jai Kumar");
33.
34. Answer ans4=new Answer();
35. ans4.setAnswername("Servlet is an API");
36. ans4.setPostedBy("Arun");
37.
38. ArrayList<Answer> list1=new ArrayList<Answer>();
39. list1.add(ans1);
40. list1.add(ans2);
41.
42. ArrayList<Answer> list2=new ArrayList<Answer>();
43. list2.add(ans3);
44. list2.add(ans4);
45.
46. Question question1=new Question();
47. question1.setQname("What is Java?");
48. question1.setAnswers(list1);
49.
50. Question question2=new Question();
51. question2.setQname("What is Servlet?");
52. question2.setAnswers(list2);
53.
54. session.persist(question1);
55. session.persist(question2);
56.
57. t.commit();
58. session.close();
59. System.out.println("success");
60. }
61. }
OUTPUT
FetchData.java
1. package com.javatpoint;
2. import java.util.*;
3. import javax.persistence.TypedQuery;
4. import org.hibernate.*;
5. import org.hibernate.boot.Metadata;
6. import org.hibernate.boot.MetadataSources;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9.
10. public class FetchData {
11. public static void main(String[] args) {
12.
13. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
14. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
15.
16. SessionFactory factory=meta.getSessionFactoryBuilder().build();
17. Session session=factory.openSession();
18.
19. TypedQuery query=session.createQuery("from Question");
20. List<Question> list=query.getResultList();
21.
22. Iterator<Question> itr=list.iterator();
23. while(itr.hasNext()){
24. Question q=itr.next();
25. System.out.println("Question Name: "+q.getQname());
26.
27. //printing answers
28. List<Answer> list2=q.getAnswers();
29. Iterator<Answer> itr2=list2.iterator();
30. while(itr2.hasNext())
31. {
32. Answer a=itr2.next();
33. System.out.println(a.getAnswername()+":"+a.getPostedBy());
34. }
35. }
36. session.close();
37. System.out.println("success");
38. }
39. }
OUTPUT
Here, we are using the scenario of Forum where one question has multiple answers.
In such case, there can be many answers for a question and each answer may have its own
information that is why we have used list in the persistent class (containing the reference of
Answer class) to represent a collection of answers.
Question.java
1. package com.javatpoint;
2. import javax.persistence.*;
3. import java.util.List;
4.
5. @Entity
6. @Table(name="q5991")
7. public class Question {
8.
9. @Id
10. @GeneratedValue(strategy=GenerationType.TABLE)
11. private int id;
12. private String qname;
13.
14. @OneToMany(cascade = CascadeType.ALL)
15. @JoinColumn(name="qid")
16. @OrderColumn(name="type")
17. private List<Answer> answers;
18. public int getId() {
19. return id;
20. }
21. public void setId(int id) {
22. this.id = id;
23. }
24. public String getQname() {
25. return qname;
26. }
27. public void setQname(String qname) {
28. this.qname = qname;
29. }
30. public List<Answer> getAnswers() {
31. return answers;
32. }
33. public void setAnswers(List<Answer> answers) {
34. this.answers = answers;
35. }
36. }
Answer.java
1. package com.javatpoint;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="ans5991")
7. public class Answer {
8. @Id
9. @GeneratedValue(strategy=GenerationType.TABLE)
10.
11. private int id;
12. private String answername;
13. private String postedBy;
14. public int getId() {
15. return id;
16. }
17. public void setId(int id) {
18. this.id = id;
19. }
20. public String getAnswername() {
21. return answername;
22. }
23. public void setAnswername(String answername) {
24. this.answername = answername;
25. }
26. public String getPostedBy() {
27. return postedBy;
28. }
29. public void setPostedBy(String postedBy) {
30. this.postedBy = postedBy;
31. }
32. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
6.
7. <dependency>
8. <groupId>com.oracle</groupId>
9. <artifactId>ojdbc14</artifactId>
10. <version>10.2.0.4.0</version>
11. </dependency>
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping class="com.javatpoint.Question"/>
16. </session-factory>
17.
18. </hibernate-configuration>
1. package com.javatpoint;
2.
3. import java.util.ArrayList;
4.
5. import org.hibernate.Session;
6. import org.hibernate.SessionFactory;
7. import org.hibernate.Transaction;
8. import org.hibernate.boot.Metadata;
9. import org.hibernate.boot.MetadataSources;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12. public class StoreData {
13. public static void main(String[] args) {
14.
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. Transaction t=session.beginTransaction();
22.
23. Answer ans1=new Answer();
24. ans1.setAnswername("Java is a programming language");
25. ans1.setPostedBy("Ravi Malik");
26.
27. Answer ans2=new Answer();
28. ans2.setAnswername("Java is a platform");
29. ans2.setPostedBy("Sudhir Kumar");
30.
31. Answer ans3=new Answer();
32. ans3.setAnswername("Servlet is an Interface");
33. ans3.setPostedBy("Jai Kumar");
34.
35. Answer ans4=new Answer();
36. ans4.setAnswername("Servlet is an API");
37. ans4.setPostedBy("Arun");
38.
39. ArrayList<Answer> list1=new ArrayList<Answer>();
40. list1.add(ans1);
41. list1.add(ans2);
42.
43. ArrayList<Answer> list2=new ArrayList<Answer>();
44. list2.add(ans3);
45. list2.add(ans4);
46.
47. Question question1=new Question();
48. question1.setQname("What is Java?");
49. question1.setAnswers(list1);
50.
51. Question question2=new Question();
52. question2.setQname("What is Servlet?");
53. question2.setAnswers(list2);
54.
55. session.persist(question1);
56. session.persist(question2);
57.
58. t.commit();
59. session.close();
60. System.out.println("success");
61. }
62. }
Note - Using these annotations in a similar way, we can also perform one-to-many association for
set, map and bag objects.
Output
1. package com.javatpoint;
2. import java.util.*;
3. import javax.persistence.TypedQuery;
4. import org.hibernate.*;
5. import org.hibernate.boot.Metadata;
6. import org.hibernate.boot.MetadataSources;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9.
10. public class FetchData {
11. public static void main(String[] args) {
12.
13. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
14. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
15.
16. SessionFactory factory=meta.getSessionFactoryBuilder().build();
17. Session session=factory.openSession();
18.
19. TypedQuery query=session.createQuery("from Question");
20. List<Question> list=query.getResultList();
21.
22. Iterator<Question> itr=list.iterator();
23. while(itr.hasNext()){
24. Question q=itr.next();
25. System.out.println("Question Name: "+q.getQname());
26.
27. //printing answers
28. List<Answer> list2=q.getAnswers();
29. Iterator<Answer> itr2=list2.iterator();
30. while(itr2.hasNext())
31. {
32. Answer a=itr2.next();
33. System.out.println(a.getAnswername()+":"+a.getPostedBy());
34. }
35. }
36. session.close();
37. System.out.println("success");
38. }
39. }
Output
Question.java
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
8. private List<Answer> answers;
9.
10. public int getId() {
11. return id;
12. }
13. public void setId(int id) {
14. this.id = id;
15. }
16. public String getQname() {
17. return qname;
18. }
19. public void setQname(String qname) {
20. this.qname = qname;
21. }
22. public List<Answer> getAnswers() {
23. return answers;
24. }
25. public void setAnswers(List<Answer> answers) {
26. this.answers = answers;
27. }
28. }
Answer.java
1. package com.javatpoint;
2.
3. import java.util.*;
4.
5. public class Answer {
6. private int id;
7. private String answername;
8. private String postedBy;
9. private List<Question> questions;
10. public int getId() {
11. return id;
12. }
13. public void setId(int id) {
14. this.id = id;
15. }
16. public String getAnswername() {
17. return answername;
18. }
19. public void setAnswername(String answername) {
20. this.answername = answername;
21. }
22. public String getPostedBy() {
23. return postedBy;
24. }
25. public void setPostedBy(String postedBy) {
26. this.postedBy = postedBy;
27. }
28. public List<Question> getQuestions() {
29. return questions;
30. }
31. public void setQuestions(List<Question> questions) {
32. this.questions = questions;
33. }
34. }
question.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7.
8. <class name="com.javatpoint.Question" table="ques1911">
9. <id name="id" type="int">
10. <column name="q_id" />
11. <generator class="increment" />
12. </id>
13. <property name="qname" />
14.
15. <list name="answers" table="ques_ans1911" fetch="select" cascade="all">
16. <key column="q_id" />
17. <index column="type"></index>
18. <many-to-many class="com.javatpoint.Answer" column="ans_id" />
19. </list>
20. </class>
21. </hibernate-mapping>
answer.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Answer" table="ans1911">
8. <id name="id" type="int">
9. <column name="ans_id" />
10. <generator class="increment" />
11. </id>
12. <property name="answername" />
13. <property name="postedBy" />
14. </class>
15. </hibernate-mapping>
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">create</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="question.hbm.xml"/>
16. <mapping resource="answer.hbm.xml"/>
17. </session-factory>
18.
19. </hibernate-configuration>
1. package com.javatpoint;
2. import java.util.ArrayList;
3. import org.hibernate.*;
4. import org.hibernate.boot.Metadata;
5. import org.hibernate.boot.MetadataSources;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8.
9. public class StoreData {
10. public static void main(String[] args) {
11.
12. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
13. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
14. SessionFactory factory=meta.getSessionFactoryBuilder().build();
15. Session session=factory.openSession();
16. Transaction t=session.beginTransaction();
17.
18. Answer ans1=new Answer();
19. ans1.setAnswername("Java is a programming language");
20. ans1.setPostedBy("Ravi Malik");
21.
22. Answer ans2=new Answer();
23. ans2.setAnswername("Java is a platform");
24. ans2.setPostedBy("Sudhir Kumar");
25.
26. Question q1=new Question();
27. q1.setQname("What is Java?");
28. ArrayList<Answer> l1=new ArrayList<Answer>();
29. l1.add(ans1);
30. l1.add(ans2);
31. q1.setAnswers(l1);
32.
33. Answer ans3=new Answer();
34. ans3.setAnswername("Servlet is an Interface");
35. ans3.setPostedBy("Jai Kumar");
36.
37. Answer ans4=new Answer();
38. ans4.setAnswername("Servlet is an API");
39. ans4.setPostedBy("Arun");
40.
41. Question q2=new Question();
42. q2.setQname("What is Servlet?");
43. ArrayList<Answer> l2=new ArrayList<Answer>();
44. l2.add(ans3);
45. l2.add(ans4);
46. q2.setAnswers(l2);
47. session.persist(q1);
48. session.persist(q2);
49.
50. t.commit();
51. session.close();
52. System.out.println("success");
53. }
54. }
Output
We can map many to many relation either using list, set, bag, map etc. Here, we are going
to use list for many-to-many mapping. In such case, three tables will be created.
1. package com.javatpoint;
2.
3. import java.util.List;
4. import javax.persistence.*;
5.
6. @Entity
7. @Table(name="ques1123")
8. public class Question {
9. @Id
10. @GeneratedValue(strategy=GenerationType.AUTO)
11. private int id;
12. private String qname;
13.
14. @ManyToMany(targetEntity = Answer.class, cascade = { CascadeType.ALL })
15. @JoinTable(name = "q_ans1123",
16. joinColumns = { @JoinColumn(name = "q_id") },
17. inverseJoinColumns = { @JoinColumn(name = "ans_id") })
18. private List<Answer> answers;
19.
20. public int getId() {
21. return id;
22. }
23. public void setId(int id) {
24. this.id = id;
25. }
26. public String getQname() {
27. return qname;
28. }
29. public void setQname(String qname) {
30. this.qname = qname;
31. }
32. public List<Answer> getAnswers() {
33. return answers;
34. }
35. public void setAnswers(List<Answer> answers) {
36. this.answers = answers;
37. }
38. }
Answer.java
1. package com.javatpoint;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="ans1123")
7. public class Answer {
8.
9. @Id
10. @GeneratedValue(strategy=GenerationType.AUTO)
11. private int id;
12. private String answername;
13. private String postedBy;
14. public int getId() {
15. return id;
16. }
17. public void setId(int id) {
18. this.id = id;
19. }
20. public String getAnswername() {
21. return answername;
22. }
23. public void setAnswername(String answername) {
24. this.answername = answername;
25. }
26. public String getPostedBy() {
27. return postedBy;
28. }
29. public void setPostedBy(String postedBy) {
30. this.postedBy = postedBy;
31. }
32.
33. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
1. <dependency>
2. <groupId>com.oracle</groupId>
3. <artifactId>ojdbc14</artifactId>
4. <version>10.2.0.4.0</version>
5. </dependency>
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">create</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping class="com.javatpoint.Question"/>
16. <mapping class="com.javatpoint.Answer"/>
17. </session-factory>
18.
19. </hibernate-configuration>
1. package com.javatpoint;
2. import java.util.ArrayList;
3. import org.hibernate.*;
4. import org.hibernate.boot.Metadata;
5. import org.hibernate.boot.MetadataSources;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8.
9. public class StoreData {
10. public static void main(String[] args) {
11.
12. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
13. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
14. SessionFactory factory=meta.getSessionFactoryBuilder().build();
15. Session session=factory.openSession();
16. Transaction t=session.beginTransaction();
17.
18. Answer an1=new Answer();
19. an1.setAnswername("Java is a programming language");
20. an1.setPostedBy("Ravi Malik");
21.
22. Answer an2=new Answer();
23. an2.setAnswername("Java is a platform");
24. an2.setPostedBy("Sudhir Kumar");
25.
26. Question q1=new Question();
27. q1.setQname("What is Java?");
28. ArrayList<Answer> l1=new ArrayList<Answer>();
29. l1.add(an1);
30. l1.add(an2);
31. q1.setAnswers(l1);
32.
33.
34. Answer ans3=new Answer();
35. ans3.setAnswername("Servlet is an Interface");
36. ans3.setPostedBy("Jai Kumar");
37.
38. Answer ans4=new Answer();
39. ans4.setAnswername("Servlet is an API");
40. ans4.setPostedBy("Arun");
41.
42. Question q2=new Question();
43. q2.setQname("What is Servlet?");
44. ArrayList<Answer> l2=new ArrayList<Answer>();
45. l2.add(ans3);
46. l2.add(ans4);
47. q2.setAnswers(l2);
48.
49. session.persist(q1);
50. session.persist(q2);
51.
52. t.commit();
53. session.close();
54. System.out.println("success");
55.
56.
57. }
58. }
Output
Here, we are going to perform one to one mapping by one-to-one element. In such case, no
foreign key is created in the primary table.
In this example, one employee can have one address and one address belongs to one
employee only. Here, we are using bidirectional association. Let's look at the persistent
classes.
Employee.java
1. package com.javatpoint;
2.
3. public class Employee {
4. private int employeeId;
5. private String name,email;
6. private Address address;
7. //setters and getters
8. }
Address.java
1. package com.javatpoint;
2.
3. public class Address {
4. private int addressId;
5. private String addressLine1,city,state,country;
6. private int pincode;
7. private Employee employee;
8. //setters and getters
9. }
employee.hbm.xml
In this mapping file we are using one-to-one element in both the mapping files to make
the one to one mapping.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Employee" table="emp212">
8. <id name="employeeId">
9. <generator class="increment"></generator>
10. </id>
11. <property name="name"></property>
12. <property name="email"></property>
13.
14. <one-to-one name="address" cascade="all"></one-to-one>
15. </class>
16.
17. </hibernate-mapping>
address.hbm.xml
This is the simple mapping file for the Address class. But the important thing is generator
class. Here, we are using foreign generator class that depends on the Employee class
primary key.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Address" table="address212">
8. <id name="addressId">
9. <generator class="foreign">
10. <param name="property">employee</param>
11. </generator>
12. </id>
13. <property name="addressLine1"></property>
14. <property name="city"></property>
15. <property name="state"></property>
16. <property name="country"></property>
17. <property name="pincode"></property>
18.
19. <one-to-one name="employee"></one-to-one>
20. </class>
21.
22. </hibernate-mapping>
3) Configuration file
This file contains information about the database and mapping file.
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="employee.hbm.xml"/>
16. <mapping resource="address.hbm.xml"/>
17. </session-factory>
18.
19. </hibernate-configuration>
Output
Fetch.java
1. package com.javatpoint;
2.
3. import java.util.*;
4. import javax.persistence.TypedQuery;
5. import org.hibernate.Session;
6. import org.hibernate.SessionFactory;
7. import org.hibernate.boot.Metadata;
8. import org.hibernate.boot.MetadataSources;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11.
12. public class Fetch {
13. public static void main(String[] args) {
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. TypedQuery query=session.createQuery("from Employee e");
21. List<Employee> list=query.getResultList();
22.
23. Iterator<Employee> itr=list.iterator();
24. while(itr.hasNext()){
25. Employee emp=itr.next();
26. System.out.println(emp.getEmployeeId()+" "+emp.getName()+"
"+emp.getEmail());
27. Address address=emp.getAddress();
28. System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+
29. address.getState()+" "+address.getCountry()+" "+address.getPincode());
30. }
31.
32. session.close();
33. System.out.println("success");
34. }
35. }
Output
In this example, one employee can have one address and one address belongs to one
employee only. Here, we are using bidirectional association. Let's look at the persistent
classes.
Employee.java
1. package com.javatpoint;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name="emp220")
6. public class Employee {
7.
8. @Id
9. @GeneratedValue(strategy=GenerationType.AUTO)
10. @PrimaryKeyJoinColumn
11. private int employeeId;
12. private String name,email;
13. @OneToOne(targetEntity=Address.class,cascade=CascadeType.ALL)
14. private Address address;
15. public int getEmployeeId() {
16. return employeeId;
17. }
18. public void setEmployeeId(int employeeId) {
19. this.employeeId = employeeId;
20. }
21. public String getName() {
22. return name;
23. }
24. public void setName(String name) {
25. this.name = name;
26. }
27. public String getEmail() {
28. return email;
29. }
30. public void setEmail(String email) {
31. this.email = email;
32. }
33. public Address getAddress() {
34. return address;
35. }
36. public void setAddress(Address address) {
37. this.address = address;
38. }
39.
40. }
Address.java
1. package com.javatpoint;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name="address220")
6. public class Address {
7.
8. @Id
9. @GeneratedValue(strategy=GenerationType.AUTO)
10. private int addressId;
11. private String addressLine1,city,state,country;
12. private int pincode;
13.
14. @OneToOne(targetEntity=Employee.class)
15. private Employee employee;
16. public int getAddressId() {
17. return addressId;
18. }
19. public void setAddressId(int addressId) {
20. this.addressId = addressId;
21. }
22. public String getAddressLine1() {
23. return addressLine1;
24. }
25. public void setAddressLine1(String addressLine1) {
26. this.addressLine1 = addressLine1;
27. }
28. public String getCity() {
29. return city;
30. }
31. public void setCity(String city) {
32. this.city = city;
33. }
34. public String getState() {
35. return state;
36. }
37. public void setState(String state) {
38. this.state = state;
39. }
40. public String getCountry() {
41. return country;
42. }
43. public void setCountry(String country) {
44. this.country = country;
45. }
46. public int getPincode() {
47. return pincode;
48. }
49. public void setPincode(int pincode) {
50. this.pincode = pincode;
51. }
52. public Employee getEmployee() {
53. return employee;
54. }
55. public void setEmployee(Employee employee) {
56. this.employee = employee;
57. }
58. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
1. <dependency>
2. <groupId>com.oracle</groupId>
3. <artifactId>ojdbc14</artifactId>
4. <version>10.2.0.4.0</version>
5. </dependency>
3) Configuration file
This file contains information about the database and mapping file.
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping class="com.javatpoint.Address"/>
16. <mapping class="com.javatpoint.Employee"/>
17. </session-factory>
18.
19. </hibernate-configuration>
1. package com.javatpoint;
2.
3. import org.hibernate.*;
4. import org.hibernate.boot.Metadata;
5. import org.hibernate.boot.MetadataSources;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8.
9. public class Store {
10. public static void main(String[] args) {
11.
12. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
13. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
14.
15. SessionFactory factory=meta.getSessionFactoryBuilder().build();
16. Session session=factory.openSession();
17.
18. Transaction t=session.beginTransaction();
19.
20. Employee e1=new Employee();
21. e1.setName("Ravi Malik");
22. e1.setEmail("[email protected]");
23.
24. Address address1=new Address();
25. address1.setAddressLine1("G-21,Lohia nagar");
26. address1.setCity("Ghaziabad");
27. address1.setState("UP");
28. address1.setCountry("India");
29. address1.setPincode(201301);
30.
31. e1.setAddress(address1);
32. address1.setEmployee(e1);
33.
34. session.persist(e1);
35. t.commit();
36.
37. session.close();
38. System.out.println("success");
39. }
40. }
Output
Fetch.java
1. package com.javatpoint;
2. import java.util.Iterator;
3. import java.util.List;
4.
5. import javax.persistence.TypedQuery;
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.boot.Metadata;
9. import org.hibernate.boot.MetadataSources;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12.
13. public class Fetch {
14. public static void main(String[] args) {
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. TypedQuery query=session.createQuery("from Employee");
22. List<Employee> list=query.getResultList();
23.
24. Iterator<Employee> itr=list.iterator();
25. while(itr.hasNext()){
26. Employee emp=itr.next();
27. System.out.println(emp.getEmployeeId()+" "+emp.getName()+"
"+emp.getEmail());
28. Address address=emp.getAddress();
29. System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+
30. address.getState()+" "+address.getCountry()+" "+address.getPincode());
31. }
32.
33. session.close();
34. System.out.println("success");
35. }
36. }
Output
In this example, every employee has one company address only and one address belongs to
many employees. Here, we are going to perform many to one mapping using XML.
Employee.java
1. package com.javatpoint;
2.
3. public class Employee {
4. private int employeeId;
5. private String name,email;
6. private Address address;
7. //setters and getters
8. }
Address.java
1. package com.javatpoint;
2.
3. public class Address {
4. private int addressId;
5. private String addressLine1,city,state,country;
6. private int pincode;
7. private Employee employee;
8. //setters and getters
9. }
employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Employee" table="emp22">
8. <id name="employeeId">
9. <generator class="increment"></generator>
10. </id>
11. <property name="name"></property>
12. <property name="email"></property>
13.
14. <many-to-one name="address" cascade="all"></many-to-one>
15. </class>
16.
17. </hibernate-mapping>
address.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Address" table="address22">
8. <id name="addressId">
9. <generator class="increment"></generator>
10. </id>
11. <property name="addressLine1"></property>
12. <property name="city"></property>
13. <property name="state"></property>
14. <property name="country"></property>
15. <property name="pincode"></property>
16. </class>
17. </hibernate-mapping>
3) Configuration file
This file contains information about the database and mapping file.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping resource="employee.hbm.xml"/>
16. <mapping resource="address.hbm.xml"/>
17. </session-factory>
18.
19. </hibernate-configuration>
Output
Fetch.java
1. package com.javatpoint;
2. import java.util.Iterator;
3. import java.util.List;
4.
5. import javax.persistence.TypedQuery;
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.boot.Metadata;
9. import org.hibernate.boot.MetadataSources;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12.
13. public class Fetch {
14. public static void main(String[] args) {
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. TypedQuery query=session.createQuery("from Employee e");
22. List<Employee> list=query.getResultList();
23.
24. Iterator<Employee> itr=list.iterator();
25. while(itr.hasNext()){
26. Employee emp=itr.next();
27. System.out.println(emp.getEmployeeId()+" "+emp.getName()+"
"+emp.getEmail());
28. Address address=emp.getAddress();
29. System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+
30. address.getState()+" "+address.getCountry()+" "+address.getPincode());
31. }
32.
33. session.close();
34. System.out.println("success");
35. }
36. }
Output
Employee.java
1. package com.javatpoint;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name="emp107")
6. public class Employee {
7. @Id
8. @GeneratedValue(strategy=GenerationType.AUTO)
9. private int employeeId;
10. private String name,email;
11. @ManyToOne(cascade=CascadeType.ALL)
12. private Address address;
13. public int getEmployeeId() {
14. return employeeId;
15. }
16. public void setEmployeeId(int employeeId) {
17. this.employeeId = employeeId;
18. }
19. public String getName() {
20. return name;
21. }
22. public void setName(String name) {
23. this.name = name;
24. }
25. public String getEmail() {
26. return email;
27. }
28. public void setEmail(String email) {
29. this.email = email;
30. }
31. public Address getAddress() {
32. return address;
33. }
34. public void setAddress(Address address) {
35. this.address = address;
36. }
37. }
Address.java
1. package com.javatpoint;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="address107")
7. public class Address {
8. @Id
9. @GeneratedValue(strategy=GenerationType.AUTO)
10. private int addressId;
11. private String addressLine1,city,state,country;
12. private int pincode;
13. @OneToOne(cascade=CascadeType.ALL)
14. private Employee employee;
15. public int getAddressId() {
16. return addressId;
17. }
18. public void setAddressId(int addressId) {
19. this.addressId = addressId;
20. }
21. public String getAddressLine1() {
22. return addressLine1;
23. }
24. public void setAddressLine1(String addressLine1) {
25. this.addressLine1 = addressLine1;
26. }
27. public String getCity() {
28. return city;
29. }
30. public void setCity(String city) {
31. this.city = city;
32. }
33. public String getState() {
34. return state;
35. }
36. public void setState(String state) {
37. this.state = state;
38. }
39. public String getCountry() {
40. return country;
41. }
42. public void setCountry(String country) {
43. this.country = country;
44. }
45. public int getPincode() {
46. return pincode;
47. }
48. public void setPincode(int pincode) {
49. this.pincode = pincode;
50. }
51. public Employee getEmployee() {
52. return employee;
53. }
54. public void setEmployee(Employee employee) {
55. this.employee = employee;
56. }
57. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
1. <dependency>
2. <groupId>com.oracle</groupId>
3. <artifactId>ojdbc14</artifactId>
4. <version>10.2.0.4.0</version>
5. </dependency>
3) Configuration file
This file contains information about the database and mapping file.
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">create</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping class="com.javatpoint.Address"/>
16. <mapping class="com.javatpoint.Employee"/>
17. </session-factory>
18.
19. </hibernate-configuration>
Fetch.java
1. package com.javatpoint;
2. import java.util.Iterator;
3. import java.util.List;
4.
5. import javax.persistence.TypedQuery;
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.boot.Metadata;
9. import org.hibernate.boot.MetadataSources;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12.
13. public class Fetch {
14. public static void main(String[] args) {
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. TypedQuery query=session.createQuery("from Employee e");
22. List<Employee> list=query.getResultList();
23.
24. Iterator<Employee> itr=list.iterator();
25. while(itr.hasNext()){
26. Employee emp=itr.next();
27. System.out.println(emp.getEmployeeId()+" "+emp.getName()+"
"+emp.getEmail());
28. Address address=emp.getAddress();
29. System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+
30. address.getState()+" "+address.getCountry()+" "+address.getPincode());
31. }
32.
33. session.close();
34. System.out.println("success");
35. }
36. }
Output
Output
In this example, every employee has one company address only and one address belongs to
many employees. Here, we are going to perform many to one mapping using annotation.
Employee.java
1. package com.javatpoint;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name="emp107")
6. public class Employee {
7. @Id
8. @GeneratedValue(strategy=GenerationType.AUTO)
9. private int employeeId;
10. private String name,email;
11. @ManyToOne(cascade=CascadeType.ALL)
12. private Address address;
13. public int getEmployeeId() {
14. return employeeId;
15. }
16. public void setEmployeeId(int employeeId) {
17. this.employeeId = employeeId;
18. }
19. public String getName() {
20. return name;
21. }
22. public void setName(String name) {
23. this.name = name;
24. }
25. public String getEmail() {
26. return email;
27. }
28. public void setEmail(String email) {
29. this.email = email;
30. }
31. public Address getAddress() {
32. return address;
33. }
34. public void setAddress(Address address) {
35. this.address = address;
36. }
37. }
Address.java
1. package com.javatpoint;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="address107")
7. public class Address {
8. @Id
9. @GeneratedValue(strategy=GenerationType.AUTO)
10. private int addressId;
11. private String addressLine1,city,state,country;
12. private int pincode;
13. @OneToOne(cascade=CascadeType.ALL)
14. private Employee employee;
15. public int getAddressId() {
16. return addressId;
17. }
18. public void setAddressId(int addressId) {
19. this.addressId = addressId;
20. }
21. public String getAddressLine1() {
22. return addressLine1;
23. }
24. public void setAddressLine1(String addressLine1) {
25. this.addressLine1 = addressLine1;
26. }
27. public String getCity() {
28. return city;
29. }
30. public void setCity(String city) {
31. this.city = city;
32. }
33. public String getState() {
34. return state;
35. }
36. public void setState(String state) {
37. this.state = state;
38. }
39. public String getCountry() {
40. return country;
41. }
42. public void setCountry(String country) {
43. this.country = country;
44. }
45. public int getPincode() {
46. return pincode;
47. }
48. public void setPincode(int pincode) {
49. this.pincode = pincode;
50. }
51. public Employee getEmployee() {
52. return employee;
53. }
54. public void setEmployee(Employee employee) {
55. this.employee = employee;
56. }
57. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
1. <dependency>
2. <groupId>com.oracle</groupId>
3. <artifactId>ojdbc14</artifactId>
4. <version>10.2.0.4.0</version>
5. </dependency>
3) Configuration file
This file contains information about the database and mapping file.
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">create</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping class="com.javatpoint.Address"/>
16. <mapping class="com.javatpoint.Employee"/>
17. </session-factory>
18.
19. </hibernate-configuration>
OUTPUT
Fetch.java
1. package com.javatpoint;
2. import java.util.Iterator;
3. import java.util.List;
4.
5. import javax.persistence.TypedQuery;
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.boot.Metadata;
9. import org.hibernate.boot.MetadataSources;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12.
13. public class Fetch {
14. public static void main(String[] args) {
15. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
16. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
17.
18. SessionFactory factory=meta.getSessionFactoryBuilder().build();
19. Session session=factory.openSession();
20.
21. TypedQuery query=session.createQuery("from Employee e");
22. List<Employee> list=query.getResultList();
23.
24. Iterator<Employee> itr=list.iterator();
25. while(itr.hasNext()){
26. Employee emp=itr.next();
27. System.out.println(emp.getEmployeeId()+" "+emp.getName()+"
"+emp.getEmail());
28. Address address=emp.getAddress();
29. System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+
30. address.getState()+" "+address.getCountry()+" "+address.getPincode());
31. }
32.
33. session.close();
34. System.out.println("success");
35. }
36. }
Output
Output
idirectional Association
Bidirectional association allows us to fetch details of dependent object from both side. In
such case, we have the reference of two classes in each other.
Let's take an example of Employee and Address, if Employee class has-a reference of
Address and Address has a reference of Employee. Additionally, you have applied one-to-
one or one-to-many relationship for the classes in mapping file as well, it is known as
bidirectional association.
Visit our one-to-one and one-to-many mapping pages to learn about it.
To use lazy collection, you may optionally use lazy="true" attribute in your collection. It is
by default true, so you don't need to do this. If you set it to false, all the child objects will
be loaded initially which will decrease performance in case of big data.
Let's see the hibernate mapping file where we have used lazy="true" attribute.
1. <list name="answers" lazy="true">
2. <key column="qid"></key>
3. <index column="type"></index>
4. <one-to-many class="com.javatpoint.Answer"/>
5. </list>
Component Mapping
1. Component Mapping
2. Example of Component Mapping
1. package com.javatpoint;
2.
3. public class Address {
4. private String city,country;
5. private int pincode;
6.
7. //getters and setters
8. }
1. package com.javatpoint;
2. public class Employee {
3. private int id;
4. private String name;
5. private Address address;//HAS-A
6.
7. //getters and setters
8. }
Here, address is a dependent object. Hibernate framework provides the facility to map the
dependent object as a component. Let's see how can we map this dependent object in
mapping file.
1. ...
2. <class name="com.javatpoint.Employee" table="emp177">
3. <id name="id">
4. <generator class="increment"></generator>
5. </id>
6. <property name="name"></property>
7.
8. <component name="address" class="com.javatpoint.Address">
9. <property name="city"></property>
10. <property name="country"></property>
11. <property name="pincode"></property>
12. </component>
13.
14. </class>
15. ...
A transaction simply represents a unit of work. In such case, if one step fails, the whole
transaction fails (which is termed as atomicity). A transaction can be described by ACID
properties (Atomicity, Consistency, Isolation and Durability).
1. Session session = null;
2. Transaction tx = null;
3.
4. try {
5. session = sessionFactory.openSession();
6. tx = session.beginTransaction();
7. //some action
8.
9. tx.commit();
10.
11. }catch (Exception ex) {
12. ex.printStackTrace();
13. tx.rollback();
14. }
15. finally {session.close();}
Hibernate Query Language (HQL)
1. Hibernate Query Language
2. Advantage of HQL
3. Query Interface
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it
doesn't depends on the table of the database. Instead of table name, we use class name in
HQL. So it is database independent query language.
Advantage of HQL
There are many advantages of HQL. They are as follows:
o database independent
o supports polymorphic queries
o easy to learn for Java Programmer
Query Interface
It is an object oriented representation of Hibernate Query. The object of Query can be
obtained by calling the createQuery() method Session interface.
The query interface provides many methods. There is given commonly used methods:
The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the
specific criteria. The Criteria interface provides methods to apply criteria such as retreiving
all the records of table whose salary is greater than 50000 etc.
Advantage of HCQL
The HCQL provides methods to add criteria, so it is easy for the java programmer to add
criteria. The java programmer is able to add many criteria on a query.
Criteria Interface
The Criteria interface provides many methods to specify criteria. The object of Criteria can
be obtained by calling the createCriteria() method of Session interface.
Syntax of createCriteria() method of Session interface
1. public Criteria createCriteria(Class c)
Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used
methods of Restrictions class are as follows:
1. Criteria c=session.createCriteria(Emp.class);
2. c.setProjection(Projections.property("name"));
3. List list=c.list();
The hibernate named query is way to use any query by some meaningful name. It is like
using alias names. The Hibernate framework provides the concept of named queries so that
application programmer need not to scatter queries to all the java code.
o by annotation
o by mapping file.
o Employee.java
o hibernate.cfg.xml
o FetchDemo
In this example, we are assuming that there is em table in the database containing 4
columns id, name, job and salary and there are some records in this table.
Employee.java
It is a persistent class that uses annotations to define named query and marks this class as
entity.
1. package com.javatpoint;
2.
3. import javax.persistence.*;
4. import javax.persistence.Entity;
5. import javax.persistence.GeneratedValue;
6. import javax.persistence.Id;
7.
8. @NamedQueries(
9. {
10. @NamedQuery(
11. name = "findEmployeeByName",
12. query = "from Employee e where e.name = :name"
13. )
14. }
15. )
16.
17. @Entity
18. @Table(name="em")
19. public class Employee {
20.
21. public String toString(){return id+" "+name+" "+salary+" "+job;}
22.
23. int id;
24. String name;
25. int salary;
26. String job;
27. @Id
28. @GeneratedValue(strategy=GenerationType.AUTO)
29.
30. //getters and setters
31. }
hibernate.cfg.xml
It is a configuration file that stores the informations about database such as driver class,
url, username, password and mapping class etc.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>
15. <mapping class="com.javatpoint.Employee"/>
16. </session-factory>
17.
18. </hibernate-configuration>
FetchData.java
It is a java class that uses the named query and prints the informations based on the query.
The getNamedQuery method uses the named query and returns the instance of Query.
1. package com.javatpoint;
2.
3. import java.util.*;
4. import javax.persistence.*;
5. import org.hibernate.*;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11. public class Fetch {
12. public static void main(String[] args) {
13.
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
16.
17. SessionFactory factory=meta.getSessionFactoryBuilder().build();
18. Session session=factory.openSession();
19.
20. //Hibernate Named Query
21. TypedQuery query = session.getNamedQuery("findEmployeeByName");
22. query.setParameter("name","amit");
23.
24. List<Employee> employees=query.getResultList();
25.
26. Iterator<Employee> itr=employees.iterator();
27. while(itr.hasNext()){
28. Employee e=itr.next();
29. System.out.println(e);
30. }
31. session.close();
32. }
33. }
Download this hibernate example (Developed using Eclipse IDE)
In such case, you need to create hbm file that defines the named query. Other resources
are same as given in the above example except Persistent class Employee.java where you
don't need to use any annotation and hibernate.cfg.xml file where you need to specify
mapping resource of the hbm file.
emp.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Employee" table="em">
8. <id name="id">
9. <generator class="native"></generator>
10. </id>
11. <property name="name"></property>
12. <property name="job"></property>
13. <property name="salary"></property>
14. </class>
15.
16. <query name="findEmployeeByName">
17. <![CDATA[from Employee e where e.name = :name]]>
18. </query>
19.
20. </hibernate-mapping>
Employee.java
1. package com.javatpoint;
2. public class Employee {
3. int id;
4. String name;
5. int salary;
6. String job;
7. //getters and setters
8. }
hibernate.cfg.xml
1. <mapping resource="emp.hbm.xml"/>
Caching in Hibernate
1. Caching in Hibernate
2. First Level Cache
3. Second Level Cache
Hibernate caching improves the performance of the application by pooling the object in the
cache. It is useful when we have to fetch the same data multiple times.
There are mainly two types of caching: first level cache and second level cache.
Session object holds the first level cache data. It is enabled by default. The first level cache
data will not be available to entire application. An application can use many session object.
SessionFactory object holds the second level cache data. The data stored in the second level
cache will be available to entire application. But we need to enable it explicitely.
SessionFactory holds the second level cache data. It is global for all the session objects
and not enabled by default.
Different vendors have provided the implementation of Second Level Cache.
1. EH Cache
2. OS Cache
3. Swarm Cache
4. JBoss Cache
Each implementation provides different cache usage functionality. There are four ways to
use second level cache.
The cache-usage property can be applied to class or collection level in hbm.xml file. The
example to define cache usage is given below:
1. <cache usage="read-only" />
Let's see the second level cache implementation and cache usage.
JBoss Cache No No
Here, we are assuming, there is emp1012 table in the oracle database containing some records.
1. package com.javatpoint;
2. import javax.persistence.*;
3. import org.hibernate.annotations.Cache;
4. import org.hibernate.annotations.CacheConcurrencyStrategy;
5. @Entity
6. @Table(name="emp1012")
7. @Cacheable
8. @Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
9. public class Employee {
10. @Id
11. private int id;
12. private String name;
13. private float salary;
14.
15. public Employee() {}
16. public Employee(String name, float salary) {
17. super();
18. this.name = name;
19. this.salary = salary;
20. }
21. public int getId() {
22. return id;
23. }
24. public void setId(int id) {
25. this.id = id;
26. }
27. public String getName() {
28. return name;
29. }
30. public void setName(String name) {
31. this.name = name;
32. }
33. public float getSalary() {
34. return salary;
35. }
36. public void setSalary(float salary) {
37. this.salary = salary;
38. }
39. }
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.2.16.Final</version>
5. </dependency>
6.
7. <dependency>
8. <groupId>com.oracle</groupId>
9. <artifactId>ojdbc14</artifactId>
10. <version>10.2.0.4.0</version>
11. </dependency>
12.
13. <dependency>
14. <groupId>net.sf.ehcache</groupId>
15. <artifactId>ehcache</artifactId>
16. <version>2.10.3</version>
17. </dependency>
18.
19.
20. <dependency>
21. <groupId>org.hibernate</groupId>
22. <artifactId>hibernate-ehcache</artifactId>
23. <version>5.2.16.Final</version>
24. </dependency>
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.2.0//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.2.0.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="show_sql">true</property>
10. <property name="hbm2ddl.auto">update</property>
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</pr
operty>
13. <property name="connection.username">system</property>
14. <property name="connection.password">jtp</property>
15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</
property>
16.
17. <property name="cache.use_second_level_cache">true</property>
18. <property name="cache.region.factory_class">org.hibernate.cache.ehcache.
EhCacheRegionFactory</property>
19. <mapping class="com.javatpoint.Employee"/>
20. </session-factory>
21. </hibernate-configuration>
Output:
As we can see here, hibernate does not fire query twice. If you don't use second level
cache, hibernate will fire query twice because both query uses different session objects.
In this example, we going to use struts 2 framework with hibernate. You need to have jar
files for struts 2 and hibernate.
index.jsp
In this page, we have created a form using the struts tags. The action name for this form is
register.
1. <%@ taglib uri="/struts-tags" prefix="S" %>
2.
3. <S:form action="register">
4. <S:textfield name="name" label="Name"></S:textfield>
5. <S:submit value="register"></S:submit>
6.
7. </S:form>
User.java
It is a simple POJO class. Here it works as the action class for struts and persistent class for
hibernate. It calls the register method of RegisterDao class and returns success as the
string.
1. package com.javatpoint;
2.
3. public class User {
4. private int id;
5. private String name;
6. //getters and setters
7.
8. public String execute(){
9. RegisterDao.saveUser(this);
10. return "success";
11. }
12.
13. }
RegisterDao.java
It is a java class that saves the object of User class using the Hibernate framework.
1. package com.javatpoint;
2.
3. import org.hibernate.Session;
4. import org.hibernate.Transaction;
5. import org.hibernate.cfg.Configuration;
6.
7. public class RegisterDao {
8.
9. public static int saveUser(User u){
10.
11. Session session=new Configuration().
12. configure("hibernate.cfg.xml").buildSessionFactory().openSession();
13.
14. Transaction t=session.beginTransaction();
15. int i=(Integer)session.save(u);
16. t.commit();
17. session.close();
18.
19. return i;
20.
21. }
22.
23. }
user.hbm.xml
This mapping file contains all the information of the persitent class.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.User" table="user451">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11. <property name="name"></property>
12. </class>
13.
14. </hibernate-mapping>
hibernate.cfg.xml
This configuration file contains informations about the database and mapping file. Here, we
are using the hb2ddl.auto property, so you don't need to create the table in the database.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5.
6. <!-- Generated by MyEclipse Hibernate Tools. -->
7. <hibernate-configuration>
8.
9. <session-factory>
10. <property name="hbm2ddl.auto">update</property>
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
13. <property name="connection.username">system</property>
14. <property name="connection.password">oracle</property>
15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
16. <mapping resource="user.hbm.xml"/>
17.
18. </session-factory>
19.
20. </hibernate-configuration>
struts.xml
This files contains information about the action class to be invoked. Here the action class is
User.
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation
3. //DTD Struts Configuration 2.1//EN"
4. "http://struts.apache.org/dtds/struts-2.1.dtd">
5. <struts>
6.
7. <package name="abc" extends="struts-default">
8. <action name="register" class="com.javatpoint.User">
9. <result name="success">welcome.jsp</result>
10. </action>
11. </package>
12. </struts>
welcome.jsp
It is the welcome file, that displays the welcome message with username.
1. <%@ taglib uri="/struts-tags" prefix="S" %>
2.
3. Welcome: <S:property value="name"/>
web.xml
It is web.xml file that contains the information about the controller. In case of Struts2,
StrutsPrepareAndExecuteFilter class works as the controller.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5"
3. xmlns="http://java.sun.com/xml/ns/javaee"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
7. <welcome-file-list>
8. <welcome-file>index.jsp</welcome-file>
9. </welcome-file-list>
10. <filter>
11. <filter-name>struts2</filter-name>
12. <filter-class>
13. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
14. </filter-class>
15. </filter>
16. <filter-mapping>
17. <filter-name>struts2</filter-name>
18. <url-pattern>/*</url-pattern>
19. </filter-mapping>
20. </web-app>
But if we are going to integrate the hibernate application with spring, we don't need to
create the hibernate.cfg.xml file. We can provide all the information in the
applicationContext.xml file.
1. //creating configuration
2. Configuration cfg=new Configuration();
3. cfg.configure("hibernate.cfg.xml");
4.
5. //creating seession factory object
6. SessionFactory factory=cfg.buildSessionFactory();
7.
8. //creating session object
9. Session session=factory.openSession();
10.
11. //creating transaction object
12. Transaction t=session.beginTransaction();
13.
14. Employee e1=new Employee(111,"arun",40000);
15. session.persist(e1);//persisting the object
16.
17. t.commit();//transaction is commited
18. session.close();
As you can see in the code of sole hibernate, you have to follow so many steps.
Now, you don't need to follow so many steps. You can simply write this:
1. Employee e1=new Employee(111,"arun",40000);
2. hibernateTemplate.save(e1);
2) Serializable save(Object entity) persists the given object and returns id.
5) void delete(Object entity) deletes the given object on the basis of id.
6) Object get(Class entityClass, Serializable id) returns the persistent object on the basis
7) Object load(Class entityClass, Serializable id) returns the persistent object on the basis
Steps
Let's see what are the simple steps for hibernate and spring integration:
In this example, we are using the Oracle as the database, but you may use any database.
Let's create the table in the oracle database
1. CREATE TABLE "EMP558"
2. ( "ID" NUMBER(10,0) NOT NULL ENABLE,
3. "NAME" VARCHAR2(255 CHAR),
4. "SALARY" FLOAT(126),
5. PRIMARY KEY ("ID") ENABLE
6. )
7. /
2) Employee.java
It is a simple POJO class. Here it works as the persistent class for hibernate.
1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private float salary;
7.
8. //getters and setters
9.
10. }
3) employee.hbm.xml
This mapping file contains all the information of the persistent class.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Employee" table="emp558">
8. <id name="id">
9. <generator class="assigned"></generator>
10. </id>
11.
12. <property name="name"></property>
13. <property name="salary"></property>
14. </class>
15.
16. </hibernate-mapping>
4) EmployeeDao.java
1. package com.javatpoint;
2. import org.springframework.orm.hibernate3.HibernateTemplate;
3. import java.util.*;
4. public class EmployeeDao {
5. HibernateTemplate template;
6. public void setTemplate(HibernateTemplate template) {
7. this.template = template;
8. }
9. //method to save employee
10. public void saveEmployee(Employee e){
11. template.save(e);
12. }
13. //method to update employee
14. public void updateEmployee(Employee e){
15. template.update(e);
16. }
17. //method to delete employee
18. public void deleteEmployee(Employee e){
19. template.delete(e);
20. }
21. //method to return one employee of given id
22. public Employee getById(int id){
23. Employee e=(Employee)template.get(Employee.class,id);
24. return e;
25. }
26. //method to return all employees
27. public List<Employee> getEmployees(){
28. List<Employee> list=new ArrayList<Employee>();
29. list=template.loadAll(Employee.class);
30. return list;
31. }
32. }
5) applicationContext.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9.
10. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
11. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
</property>
12. <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></propert
y>
13. <property name="username" value="system"></property>
14. <property name="password" value="oracle"></property>
15. </bean>
16.
17. <bean id="mysessionFactory" class="org.springframework.orm.hibernate3.Local
SessionFactoryBean">
18. <property name="dataSource" ref="dataSource"></property>
19.
20. <property name="mappingResources">
21. <list>
22. <value>employee.hbm.xml</value>
23. </list>
24. </property>
25.
26. <property name="hibernateProperties">
27. <props>
28. <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</pro
p>
29. <prop key="hibernate.hbm2ddl.auto">update</prop>
30. <prop key="hibernate.show_sql">true</prop>
31.
32. </props>
33. </property>
34. </bean>
35.
36. <bean id="template" class="org.springframework.orm.hibernate3.HibernateTem
plate">
37. <property name="sessionFactory" ref="mysessionFactory"></property>
38. </bean>
39.
40. <bean id="d" class="com.javatpoint.EmployeeDao">
41. <property name="template" ref="template"></property>
42. </bean>
43.
44.
45. </beans>
6) InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by passing
the object of Employee class.
1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.ClassPathResource;
6. import org.springframework.core.io.Resource;
7.
8. public class InsertTest {
9. public static void main(String[] args) {
10.
11. Resource r=new ClassPathResource("applicationContext.xml");
12. BeanFactory factory=new XmlBeanFactory(r);
13.
14. EmployeeDao dao=(EmployeeDao)factory.getBean("d");
15.
16. Employee e=new Employee();
17. e.setId(114);
18. e.setName("varun");
19. e.setSalary(50000);
20.
21. dao.saveEmployee(e);
22.
23. }
24. }
Now, if you see the table in the oracle database, record is inserted successfully.
1. <property name="hibernateProperties">
2. <props>
3. <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</pro
p>
4. <prop key="hibernate.hbm2ddl.auto">update</prop>
5. <prop key="hibernate.show_sql">true</prop>
6.
7. </props>
If you write this code, you don't need to create table because table will be created
automatically.
JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise
application. It is currently used as the replacement for complex entity beans.
The implementation of JPA specification are provided by many vendors such as:
o Hibernate
o Toplink
o iBatis
o OpenJPA etc.
In this example, we are going to use hibernate for the implementation of JPA.
In this example, we are going to integrate the hibernate application with spring. Let's see
the directory structure of jpa example with spring.
1) Account.java
1. package com.javatpoint;
2.
3. public class Account {
4. private int accountNumber;
5. private String owner;
6. private double balance;
7. //no-arg and parameterized constructor
8. //getters and setters
9. }
2) Account.xml
This mapping file contains all the information of the persistent class.
1. <entity-mappings version="1.0"
2. xmlns="http://java.sun.com/xml/ns/persistence/orm"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
5. http://java.sun.com/xml/ns/persistence/orm_1_0.xsd ">
6.
7. <entity class="com.javatpoint.Account">
8. <table name="account100"></table>
9. <attributes>
10. <id name="accountNumber">
11. <column name="accountnumber"/>
12. </id>
13. <basic name="owner">
14. <column name="owner"/>
15. </basic>
16. <basic name="balance">
17. <column name="balance"/>
18. </basic>
19. </attributes>
20. </entity>
21. </entity-mappings>
3) AccountDao.java
1. package com.javatpoint;
2. import java.util.List;
3. import org.springframework.orm.jpa.JpaTemplate;
4. import org.springframework.transaction.annotation.Transactional;
5. @Transactional
6. public class AccountsDao{
7. JpaTemplate template;
8.
9. public void setTemplate(JpaTemplate template) {
10. this.template = template;
11. }
12. public void createAccount(int accountNumber,String owner,double balance){
13. Account account = new Account(accountNumber,owner,balance);
14. template.persist(account);
15. }
16. public void updateBalance(int accountNumber,double newBalance){
17. Account account = template.find(Account.class, accountNumber);
18. if(account != null){
19. account.setBalance(newBalance);
20. }
21. template.merge(account);
22. }
23. public void deleteAccount(int accountNumber){
24. Account account = template.find(Account.class, accountNumber);
25. if(account != null)
26. template.remove(account);
27. }
28. public List<Account> getAllAccounts(){
29. List<Account> accounts =template.find("select acc from Account acc");
30. return accounts;
31. }
32. }
4) persistence.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <persistence xmlns="http://java.sun.com/xml/ns/persistence"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
5. http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
6.
7. <persistence-unit name="ForAccountsDB">
8. <mapping-file>com/javatpoint/Account.xml</mapping-file>
9. <class>com.javatpoint.Account</class>
10. </persistence-unit>
11. </persistence>
5) applicationContext.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:tx="http://www.springframework.org/schema/tx"
5. xsi:schemaLocation="http://www.springframework.org/schema/beans
6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7. http://www.springframework.org/schema/tx
8. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
9.
10. <tx:annotation-driven transaction-manager="jpaTxnManagerBean" proxy-
target-class="true"/>
11.
12. <bean id="dataSourceBean" class="org.springframework.jdbc.datasource.Driver
ManagerDataSource">
13. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
</property>
14. <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></prop
erty>
15. <property name="username" value="system"></property>
16. <property name="password" value="oracle"></property>
17. </bean>
18.
19. <bean id="hbAdapterBean" class="org.springframework.orm.jpa.vendor.Hibern
ateJpaVendorAdapter">
20. <property name="showSql" value="true"></property>
21. <property name="generateDdl" value="true"></property>
22. <property name="databasePlatform" value="org.hibernate.dialect.OracleDiale
ct"></property>
23. </bean>
24.
25. <bean id="emfBean" class="org.springframework.orm.jpa.LocalContainerEntityM
anagerFactoryBean">
26. <property name="dataSource" ref="dataSourceBean"></property>
27. <property name="jpaVendorAdapter" ref="hbAdapterBean"></property>
28. </bean>
29.
30. <bean id="jpaTemplateBean" class="org.springframework.orm.jpa.JpaTemplate"
>
31. <property name="entityManagerFactory" ref="emfBean"></property>
32. </bean>
33.
34. <bean id="accountsDaoBean" class="com.javatpoint.AccountsDao">
35. <property name="template" ref="jpaTemplateBean"></property>
36. </bean>
37. <bean id="jpaTxnManagerBean" class="org.springframework.orm.jpa.JpaTrans
actionManager">
38. <property name="entityManagerFactory" ref="emfBean"></property>
39. </bean>
40.
41. </beans>
6) Accountsclient.java
1. package com.javatpoint;
2.
3. import java.util.List;
4. import org.springframework.context.ApplicationContext;
5. import org.springframework.context.support.ClassPathXmlApplicationContext;
6. import org.springframework.context.support.FileSystemXmlApplicationContext;
7.
8. public class AccountsClient{
9. public static void main(String[] args){
10. ApplicationContext context = new ClassPathXmlApplicationContext("applicationCont
ext.xml");
11. AccountsDao accountsDao = context.getBean("accountsDaoBean",AccountsDao.clas
s);
12.
13. accountsDao.createAccount(15, "Jai Kumar", 41000);
14. accountsDao.createAccount(20, "Rishi ", 35000);
15. System.out.println("Accounts created");
16.
17. //accountsDao.updateBalance(20, 50000);
18. //System.out.println("Account balance updated");
19.
20.
21. /*List<Account> accounts = accountsDao.getAllAccounts();
22. for (int i = 0; i < accounts.size(); i++) {
23. Account acc = accounts.get(i);
24. System.out.println(acc.getAccountNumber() + " : " + acc.getOwner() + " (" + acc.
getBalance() + ")");
25. }*/
26.
27. //accountsDao.deleteAccount(111);
28. //System.out.println("Account deleted");
29.
30. }
31. }
Output
Hibernate: insert into account100 (balance, owner, accountnumber) values
(?, ?, ?)
Hibernate: insert into account100 (balance, owner, accountnumber) values
(?, ?, ?)
Accounts created