Hibernate
Hibernate
ORM
-----------------------------------------------------------
Hibernate’s primary feature is mapping from Java classes to database tables, and
mapping from Java data types to SQL data types.
Advantages of Hibernate Framework
------------------------------------
2) Fast Performance
Hibernate framework provides the facility to create the tables of the database
automatically.
The Hibernate architecture is layered to keep you isolated from having to know the
underlying APIs. Hibernate makes use of the database and configuration data to
provide persistence services (and persistent objects) to the application.
Configuration Object:
The Configuration object is the first Hibernate object you create in any Hibernate
application and usually created only once during application initialization. It
represents a configuration or properties file required by the Hibernate. The
Configuration object provides two keys components:
SessionFactory:
---------------
Session
-------------------------------------------
It is available for the whole application while a Session is only available for
particular transaction.
The session object provides an interface between the application and data stored in
the database. It is a short-lived object and wraps the JDBC connection. It is factory
of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data.
The org.hibernate.Session interface provides methods to insert, update and delete
the object. It also provides factory methods for Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
ConnectionProvider
TransactionFactory
In Hibernate, either we create an object of an entity and save it into the database, or
we fetch the data of an entity from the database. Here, each entity is associated
with the lifecycle. The entity object passes through the different stages of the
lifecycle.
o Transient state
o Persistent state
o Detached state
Transient state
PPersistent state
AAs soon as the object associated with the Session, it entered in the
persistent state.
o Hence, we can say that an object is in the persistence state when we save or
persist it.
o Here, each object represents the row of the database table.
o So, modifications in the data make changes in the database.
We can use any of the following methods for the persistent state.
1. session.save(e);
2. session.persist(e);
3. session.update(e);
4. session.saveOrUpdate(e);
5. session.lock(e);
6. session.merge(e);
Detached State
o Once we either close the session or clear its cache, then the object entered
into the detached state.
o As an object is no more associated with the Session, modifications in the
data don't affect any changes in the database.
o However, the detached object still has a representation in the database.
We can use any of the following methods for the detached state.
1. session.close();
2. session.clear();
3. session.detach(e);
o A no-arg constructor:
o Provide an identifier property: It is better to assign an attribute as id. This
attribute behaves as a primary key in database.
o Declare getter and setter methods: The Hibernate recognizes the method by
getter and setter method names by default.
o Prefer non-final class:
property : It is the sub-element of class that specifies the property name of the
Persistent class.
The configuration file contains information about the database and mapping file.
Conventionally, its name should be hibernate.cfg.xml .
----------------------------------------------------------------------------------
next
next
OR
select Artifact-id :
maven-archetype-quickstart
version : 1.1
next
Group id : com.klu
Artifact id : MavenHibernate
finish
goto src/main/java
App.java
goto src
resources
Employee.hbm.xml
hibernate.cfg.xml
3)open pom.xml
https://mvnrepository.com/
search ojdbc8
4)goto App.java
----------------------
Employee.java
-------------
App.java
-----------------------
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* Hello world!
*
*/
public class App
{
public static void main(String[] args)
{
//load configuration file
Configuration cfg = new
Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf =
cfg.buildSessionFactory();
Session s = sf.openSession();
Employee e = new Employee();
e.setEmpId(1001);
e.setEmpName("vijay");
e.setEmpDesig("Asst.Professor");
e.setEmpSal(40000);
s.save(e);
Transaction tx =
s.beginTransaction();
tx.commit();
s.close();
sf.close();
}
Employee.hbm.xml
------------------------
hibernate.cfg.xml
-------------------------
Advantage of HQL
o database independent
o supports polymorphic queries
o easy to learn for Java Programmer
Query Interface
--------------------------------------
------------------------------------------------------------------
---------------------------------------------------------------
---------------------------------------------------
App.java
--------------------
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
SessionFactory factory =
cfg.buildSessionFactory();
Session session =
factory.openSession();
/* Selecting all objects(records) */
Query qry =
session.createQuery("from Product p"); /*
Product is "pojo Class name" , not table
name */
List l =qry.list();
System.out.println("Total Number Of
Records : "+l.size());
Iterator it = l.iterator();
while(it.hasNext())
{
Object o = (Object)it.next();
Product p = (Product)o;
System.out.println("Product id :
"+p.getPid());
System.out.println("Product
Name : "+p.getPname());
System.out.println("Product Price
: "+p.getPprice());
System.out.println("----------------------"
);
}
}
}
Product.hbm.xml
-----------------
<hibernate-mapping>
<class name="com.klu.HibernateHQL.Product"
table="hbproduct23">
</class>
</hibernate-mapping>
hibernate.cfg.xml
------------------------
Table created.
PID NUMBER(10)
PNAME VARCHAR2(20)
PPRICE NUMBER(10)
1 row created.
100 marker 50
SQL> commit;
Commit complete.
---------------------------------------------------------
2. HQL and SQL both are queries in a database. In the case of HQL, the queries
are in the form of objects that are translated to SQL queries in the target database.
3. SQL works with tables and columns to manipulate the data stored in it.
4. HQL works with classes and their properties to finally be mapped to a table
structure in a database.
SQL manipulates data stored in tables and modifies its rows and columns. HQL is
concerned about objects and its properties.
SQL is concerned about the relationship that exists between two tables while HQL
considers the relation between two objects.
---HQL
---Native SQL
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 retrieving all the records of table whose salary is greater than 50000 etc
The Criteria interface, Restrictions class and Order class provides the methods and
functionality to perform HCQL operations. The Criteria interface object can be
created by createCriteria() method of Session interface.
Advantages
Criteria is also database independent, Because it internally generates HQL queries.
Criteria is suitable for executing dynamic queries
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:
Order Class
By using Order class we can sort the records in ascending or descending order.
Order class provides two different methods to make ascending and descending.
1. public static Order asc(String propertyName)
2. public static Order desc(String propertyName)
Restrictions Class
Restrictions class provides methods that can be used add restrictions (conditions)
to criteria object.
We have many methods in Restrictions class some of the commonly using
methods are.
HCQL(Hibernate Criteria Query Language)
--------------------------------------------
Product.java
-----------------
Product.hbm.xml
---------------------
hibernate.cfg.xml
-----------------------
<hibernate-configuration>
<session-factory>
<!-- connection properties -->
<property
name="connection.driver_class">oracle.jdbc.
driver.OracleDriver</property>
<property
name="connection.url">jdbc:oracle:thin:@loc
alhost:1521:xe</property>
<property
name="connection.user">system</property>
<property
name="connection.password">vijay</property>
<!-- hibernate properties -->
<property
name="show_sql">true</property>
<property
name="hibernate.dialect">org.hibernate.dial
ect.OracleDialect</property>
<property
name="hbm2ddl.auto">update</property>
<!-- mapping resources -->
<mapping
resource="Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Client.java
-------------------
import org.hibernate.*;
import org.hibernate.cfg.*;
Transaction tx =
s.beginTransaction();
s.save(p1);
s.save(p2);
s.save(p3);
tx.commit();
System.out.println("Object saved
successfully");
s.close();
sf.close();
}
}
App.java
------------------------
import java.util.*;
import org.hibernate.*;
//import org.hibernate.boot.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
while(it.hasNext())
{
Product p=(Product)it.next();
System.out.println(p.getPid());
System.out.println(p.getPname());
System.out.println(p.getPrice());
System.out.println("-----------------");
}
System.out.println("Criteria
Executed successfully");
s.close();
sf.close();
}
1. assigned
2. increment
3. sequence
Hibernate Example using Annotation
Java annotation is a form of metadata that can be added to Java source code.
Annotations basically are used to provide additional information, so
could be an alternative to XML and Java marker interfaces.
Annotations do not change the action of a compiled program.
Ex: @Override,@Inherited,etc
Hibernate Annotations are a powerful method for supplying the metadata for
mapping objects and relational tables.
The hibernate application can be created with annotation. There are many
annotations that can be used to create hibernate application such as @Entity, @Id,
@Table etc.
@Entity
-------------------------------
Used for declaring any POJO class as an entity for a database
@Id
---------------------------------
Used for declaring a primary key inside our POJO class
@Table
----------------------------------------------
goto src
goto main under src right click new folder
resources
goto resources folder right click new other
select xml file
hibernate.cfg.xml
3)open pom.xml
add hibernate jar file and ojdbc8 jar file
dependency to xml file
----open browser
https://mvnrepository.com/
4)goto App.java
run as Java application
import javax.persistence.*;
@Entity
@Table(name="emp4")
public class Employee {
@Id
@Column(name = "id")
private int id;
@Column(name = "firstname")
private String firstName;
@Column(name = "lastname")
private String 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
--------------------------------------------------------------------------
<mapping
class="com.klu.HibernateAnnotation.Employee
"/>
</session-factory>
</hibernate-configuration>
App.java
-----------------------------------------------------------------
import org.hibernate.*;
import org.hibernate.boot.*;
import org.hibernate.boot.registry.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import
org.hibernate.boot.registry.StandardService
RegistryBuilder;
/**
* Hello world!
*
*/
public class App
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
goto src
goto main under src right click new folder
resources
create 2 xml files
Employee.hbm.xml
hibernate.cfg.xml
----open browser
https://mvnrepository.com/
search ojdbc8
4)goto App.java
run as Java application
Hibernate Inheritance
---------------------------------------------------------------------------------
/* Contract_Employee Class */
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.StandardService
Registry;
import
org.hibernate.boot.registry.StandardService
RegistryBuilder;
import org.hibernate.cfg.Configuration;
Transaction
t=ss.beginTransaction();
Employee e1=new Employee();
e1.setName("Anil");
Regular_Employee e2=new
Regular_Employee();
e2.setName("Arun");
e2.setSalary(55555);
e2.setBonus(5);
Contract_Employee e3=new
Contract_Employee();
e3.setName("Ajay");
e3.setPay_per_hour(1000);
e3.setContract_duration("15
hours");
ss.persist(e1);
ss.persist(e2);
ss.persist(e3);
t.commit();
ss.close();
System.out.println("success");
}
Employee.hbm.xml
-------------------------------------------------------------------
hibernate.cfg.xml in MYSQL
----------------------------------------------------
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
</session-factory>
</hibernate-configuration>
Employee.hbm.xml
--------------------------------------------------------------
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC
"-//Hibernate/Hibernate
Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.ne
t/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class table="empl1"
name="hibernatecrud.Employee">
<id name="empId" />
<property name="empName" />
<property name="empDesig"
column="Designation" />
<property name="empSal"
column="Salary"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
-----------------------------------------------------------------------------------
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE hibernate-
configuration PUBLIC
"-//Hibernate/Hibernate
Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.ne
t/hibernate-configuration-
3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Connection Properties -->
<property
name="connection.driver_class">o
racle.jdbc.driver.OracleDriver</
property>
<property
name="connection.url">jdbc:oracl
e:thin:@localhost:1521:XE</prope
rty>
<property
name="connection.username">syste
m</property>
<property
name="connection.password">vijay
</property>
Employee.java
-------------------------------------------------------
package hibernatecrud;
public class Employee {
private int empId;
private String empName;
private String empDesig;
private double empSal;
public int getEmpId() {
return empId;
}
public void setEmpId(int
empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String
empName) {
this.empName = empName;
}
public String getEmpDesig() {
return empDesig;
}
public void
setEmpDesig(String empDesig) {
this.empDesig = empDesig;
}
public double getEmpSal() {
return empSal;
}
public void setEmpSal(double
empSal) {
this.empSal = empSal;
}
@Override
public String toString() {
return "Employee [empId=" +
empId + ", empName=" + empName +
", empDesig=" + empDesig + ",
empSal=" + empSal
+ "]";
}
}
EmployeeCreateTest
------------------------------------------------------------
package hibernatecrud;
import
org.hibernate.SessionFactory;
import
org.hibernate.cfg.Configuration;
import org.hibernate.*;
System.out.println(e.getEmpId());
System.out.println(e);
s.save(e);
s.beginTransaction().commit();
}
}
EmployeeUpdateTest
---------------------------------------------------------------------
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;
s.update(e);
System.out.println(e.getEmpId());
System.out.println(e);
s.beginTransaction().commit();
}
}
EmployeeRetrieveTestGet
-------------------------------------------------------------
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;
Employee e=(Employee)o;
System.out.println(e.getEmpId());
System.out.println(e);
}
}
EmployeeDeleteTest
---------------------------------------------------------------
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;
s.delete(e);
System.out.println(e.getEmpId());
System.out.println(e);
s.beginTransaction().commit();
}
}