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

Hibernate

Uploaded by

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

Hibernate

Uploaded by

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

JPA

JPA stands for Java Persistence API (Application Programming


Interface).
It was initially released on 11 May 2006.
Data Persistence is a means for an application to
persist and retrieve information from a non-volatile
storage system.
It is used to control data between Java objects and relational databases.
It is observed as a standard technique for Object Relational Mapping.
It is considered as a link between an object-oriented model and a
relational database system.
For data persistence, the javax.persistence package contains the JPA
classes and interfaces.

 JPA is only a specification, it is not an implementation.


 It is a set of rules and guidelines to set interfaces for implementing
object-relational mapping, .
 It needs a few classes and interfaces.
 It supports polymorphism and inheritance.

ORM

ORM stands for Object-Relational Mapping (ORM) is a programming


technique for converting data between relational databases and object
oriented programming languages such as Java, C# etc.

An Object Relational Mapping Tool provides a simple API for storing


and retrieving Java objects directly to and from the relational database.

It is responsible to store Object Model data into Relational Model and


further read the data from Relational Model into Object Model.
Advantages :
1 Transaction management and automatic key generation.
2 Fast development of application.
Java ORM Frameworks:
A persistent framework is an ORM service that stores and retrieves
objects into a relational database.
 Enterprise JavaBeans Entity Beans
 Spring DAO
 Hibernate

Popular ORM Frameworks in other programming Languages

 Python – Django, SQLAlchemy


 NodeJS
 PHP
 C# and .Net – Entity Framework
HIBERNATES

-----------------------------------------------------------

It is an open source, lightweight, ORM (Object Relational Mapping) tool.

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised


as an open source persistent framework created by Gavin King in 2001.

Hibernate is a Java framework that simplifies the development of Java application


to interact with the database.

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

------------------------------------

1) Open Source and Lightweight

Hibernate framework is open source and lightweight.

2) Fast Performance

The performance of hibernate framework is fast because cache is internally used in


hibernate framework.

3) Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL. It


generates the database independent queries. So you don't need to write database
specific queries.

4) Automatic Table Creation

Hibernate framework provides the facility to create the tables of the database
automatically.

So there is no need to create tables in the database manually.


HIBERNATE ARCHITECTURE

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.

Following is a very high level view of the Hibernate Application Architecture.

Following is a detailed view of the Hibernate Application Architecture with few


important core classes.
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA),
and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary
level of abstraction of functionality common to relational databases, allowing
almost any database with a JDBC driver to be supported by Hibernate. JNDI and
JTA allow Hibernate to be integrated with J2EE application servers.

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:

 Database Connection: This is handled through one or more configuration files


supported by Hibernate. These files
are hibernate.properties and hibernate.cfg.xml.
 Class Mapping Setup
This component creates the connection between the Java classes and database
tables..
For creating the first hibernate application, we must know the elements of Hibernate architectu

SessionFactory:
---------------

SessionFactory is a factory class for Session objects.

The SessionFactory is a factory of session and client of ConnectionProvider. It


holds second level cache (optional) of data. The org.hibernate.SessionFactory
interface provides factory method to get the object of Session.

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

It is a factory of JDBC connections. It abstracts the application from


DriverManager or DataSource. It is optional.

TransactionFactory

It is a factory of Transaction. It is optional.


Difference between JDBC & HIBERNATE

Hibernate uses HQL (Hibernate


1) JDBC enables developers to create Query Language) which is
queries and update data to a relational similar to SQL but understands
database using the Structured Query object-oriented concepts like
Language (SQL). inheritance, association etc.
2) JDBC code needs to be written in a try Whereas Hibernate manages the
catch block as it throws checked exceptions itself by marking
exception(SQLexception). them as unchecked.
Whereas Hibernate is database
3) JDBC is database dependent i.e. one independent and same code can
needs to write different codes for work for many databases with
different database. minor changes.
Associations like one-to-one,
one-to-many, many-to-one, and
many-to-many can be acquired
4) Creating associations between relations easily with the help of
is quite hard in JDBC. annotations.
Hibernate Lifecycle

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.

The Hibernate lifecycle contains the following states: -

o Transient state
o Persistent state
o Detached state
Transient state

o The transient state is the initial state of an object.


o Once we create an instance of POJO class, then the object entered in the
transient state.

1. Employee e=new Employee(); //Here, object enters in the transient state.


2. e.setId(101);
3. e.setFirstName(“vijay”);
4. e.setLastName(“kumar”);

 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);

Steps to create Hibernate Application

1. Create the Persistent class(POJO)


2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar files
6. Load ojdbc14.jar
7. Run the hibernate application

POJO-PLAIN OLD JAVA OBJECT

1) Create the Persistent class

A simple Persistent class should follow some rules:

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:

2) Create the mapping file for Persistent class

The mapping file name conventionally, should be class_name.hbm.xml. There are


many elements of the mapping file.

o hibernate-mapping : It is the root element in the mapping file that contains


all the mapping elements.
o class : It is the sub-element of the hibernate-mapping element. It specifies
the Persistent class.
o id : It is the subelement of class. It specifies the primary key attribute in the
class.
o generator : It is the sub-element of id. It is used to generate the primary key.
There are many generator classes such as assigned, increment, hilo,
sequence, native etc. We will learn all the generator classes later.

property : It is the sub-element of class that specifies the property name of the
Persistent class.

3) Create the Configuration file

The configuration file contains information about the database and mapping file.
Conventionally, its name should be hibernate.cfg.xml .

4) Create the class that retrieves or stores the object


Steps to create MAVEN Hibernate project in Eclipse

----------------------------------------------------------------------------------

1)goto file->new->project->search MAVEN

select maven project

use default workspace location select

next

select org.apache.maven.archetypes maven-archetype-quickstart version


1.1

next

OR

select Artifact-id :

maven-archetype-quickstart

version : 1.1

next

Group id : com.klu

Artifact id : MavenHibernate

finish

2)expand project folder

goto src/main/java

com.klu.HibernateMaven-->right click new class

create 2 java files


Employee.java

App.java

App.java already exist no need to create again.

goto src

goto main under src right click new folder

resources

goto resources folder right click new other

select xml file

create 2 xml files

Employee.hbm.xml

hibernate.cfg.xml

open Employee.hbm.xml file change package name.

open hibernate.cfg.xml file change database uid & password.

3)open pom.xml

add hibernate jar file and ojdbc8 jar file

dependency to xml file


----open browser

https://mvnrepository.com/

serch hibernate core jars in website

goto Hibernate Core Relocation

select 5.6.4 final jar files

goto dependency jars copy from website

and paste in pom.xml file

again search oracle driver in mvnrepository website

search ojdbc8

goto 12.2.0.1 file

select dependency file and copy from website

paste in pom.xml file

4)goto App.java

run as Java application


Hibernate application for Employee

----------------------

Employee.java

-------------

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

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

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate
-mapping-3.0.dtd">
<hibernate-mapping>
<class
name="com.klu.MavenHibernate.Employee"
table="EMP111">
<id name="empId">
<generator
class="assigned"></generator>
</id>
<property name="empName"></property>
<property name="empDesig"
column="DESIG"></property>
<property name="empSal"
column="SAL"></property>
</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.net/hibernate
-configuration-3.0.dtd">
<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.username">system</property
>
<property
name="connection.password">vijay</property>
<!-- hibernate properties -->
<property
name="dialect">org.hibernate.dialect.Oracle
Dialect</property>
<property
name="show_sql">true</property>
<property
name="hbm2ddl.auto">update</property>
<!-- mapping file configure -->
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Hibernate Query Language (HQL)

Hibernate Query Language (HQL) is an object-oriented query language, similar


to SQL, but instead of operating on tables and columns, HQL works with
persistent objects and their properties.

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

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.

In HQL, instead of a table name, it uses a class name.

Hibernate converts HQL queries into SQL queries.

HQL FROM Clause

--------------------------------------

String str = "FROM Employee";


Query q = session.createQuery(str);
List results = q.list();

String str = "SELECT e.empid FROM Employee e";


Query q = session.createQuery(str);
List results = q.list();

HQL INSERT Clause

------------------------------------------------------------------

String str = "insert into Employee(empid, empname)" +


"select empid, empname from dept";
Query q = session.createQuery(str);
int result = q.executeUpdate();

HQL UPDATE Clause

---------------------------------------------------------------

String str = "UPDATE Employee set empname=:n WHERE empid=:i";


Query q=session.createQuery(str);
q.setParameter("n","vijaykumar");
q.setParameter("i",1001);
int status=q.executeUpdate();
System.out.println(status);
HQL DELETE Clause

---------------------------------------------------

String str = "DELETE FROM Employee where empid=1001";


Query q=session.createQuery(str);
q.executeUpdate();

Product Example using HQL(Hibernate Query Language)


----------------------------------------------------------------
Product.java
-------------

public class Product {


private int pid;
private String pname;
private int pprice;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getPprice() {
return pprice;
}
public void setPprice(int pprice) {
this.pprice = pprice;
}

App.java

--------------------

import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;

public class App


{
public static void main(String[] args)
{
Configuration cfg = new
Configuration();
cfg.configure("hibernate.cfg.xml");

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

-----------------

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.klu.HibernateHQL.Product"
table="hbproduct23">

<id name="pid" column="PID" />


<property name="pname" column="PNAME"/>
<property name="pprice" column="PPRICE" />

</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.net/
hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hbm2ddl.auto">validate</property>
<property
name="dialect">org.hibernate.dialect.Oracle
10gDialect</property>
<property
name="connection.url">jdbc:oracle:thin:@loc
alhost:1521:xe</property>
<property
name="connection.username">system</property
>
<property
name="connection.password">vijay</property>
<property
name="connection.driver_class">oracle.jdbc.
driver.OracleDriver</property>
<mapping
resource="Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>

In Run SQL Command line


--------------------------------------------------------------------

SQL> create table hbproduct23(pid number(10),pname varchar2(20),pprice


number(10));

Table created.

SQL> desc hbproduct23;

Name Null? Type

----------------------------------------- -------- ----------------------------

PID NUMBER(10)

PNAME VARCHAR2(20)

PPRICE NUMBER(10)

SQL> insert into hbproduct23 values(100,'marker',50);

1 row created.

SQL> select * from hbproduct23;

PID PNAME PPRICE


---------- -------------------- ----------

100 marker 50

SQL> commit;

Commit complete.

Differences between SQL and HQL:

---------------------------------------------------------

1. HQL is similar to SQL and is also case insensitive.

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.

5. HQL supports concepts like polymorphism, inheritance, association, etc. It is a


powerful and easy-to-learn language that makes SQL object oriented.
6. You write database-type independent queries in HQL that are converted into
SQL queries at runtime.

SQL is based on a relational database model whereas HQL is a combination of


object-oriented programming with relational database concepts.

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.

HCQL (Hibernate Criteria Query Language)

Hibernate provides three different ways to retrieve data from database.

---HQL

---Native SQL

--Hibernate Criteria queries

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:

 Criteria Interface has some methods to specify criteria.


 Hibernate session interface has a method named createCriteria() to create criteria.

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

-----------------

public class Product {


public int pid;
public String pname;
public double price;
public int getPid()
{
return pid;
}
public void setPid(int pid)
{
this.pid = pid;
}
public String getPname()
{
return pname;
}
public void setPname(String pname)
{
this.pname = pname;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}

Product.hbm.xml

---------------------

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd">

<!-- hibernate mapping file -->


<hibernate-mapping>
<class
name="com.klu.HibernateHCQL.Product"
table="hbcproduct">
<id name="pid" column="PID">
<generator
class="assigned"></generator>
</id>
<property name="pname"
column="PNAME"></property>
<property name="price"
column="PRICE"></property>
</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.net/
hibernate-configuration-3.0.dtd">

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

public class Client {

public static void main(String[] args)


{
// TODO Auto-generated method stub
Configuration cfg = new
Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf =
cfg.buildSessionFactory();
Session s = sf.openSession();
Product p1 = new Product();
p1.setPid(1001);
p1.setPname("AC");
p1.setPrice(35000);
Product p2 = new Product();
p2.setPid(1002);
p2.setPname("Mobile");
p2.setPrice(16000);
Product p3 = new Product();
p3.setPid(1003);
p3.setPname("Mouse");
p3.setPrice(300);

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

public class App


{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Configuration cfg = new
Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf =
cfg.buildSessionFactory();
Session s = sf.openSession();
Criteria crit =
s.createCriteria(Product.class);
Criterion cn =
Restrictions.gt("price",new Double(10000));
crit.add(cn);
List l=crit.list();
System.out.println("List total
size..._"+l.size());
Iterator it=l.iterator();

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();
}

Difference between HQL & HCQL


 HQL is to perform both select and non-select operations on the data, but Criteria
is only for selecting the data, we cannot perform non-select operations using
criteria
 HQL-INSERT,UPDATE,DELETE,SELECT
 HCQL-SELECT
 HQL is suitable for executing Static Queries, where as Criteria is suitable for
executing Dynamic Queries
 Criteria used to take more time to execute then HQL

Generator classes in Hibernate


The <generator> class is a sub-element of id. It is used to generate the
unique identifier for the objects of persistent class.

All the generator classes implements


the org.hibernate.id.IdentifierGenerator interface.

Hibernate framework provides many built-in generator classes:

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.

Java annotations can be read from source files.

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

Used to change table details, some of the attributes are-


 name – override the table name
 schema

Steps to create MAVEN Hibernate Annotation project in Eclipse


----------------------------------------------------------------------------------
1)goto file->new->project->search MAVEN
select maven project
use default workspace location select
next
select org.apache.maven.archetypes maven-archetype-quickstart
version 1.1
next
OR
select Artifact-id :
maven-archetype-quickstart
version : 1.1
next
Group id : com.klu
Artifact id : HibernateAnnotation
finish

2)expand project folder


goto src/main/java
com.klu. HibernateAnnotation -->right click new class
create 2 java files
Employee.java
App.java
App.java already exist no need to create again.

goto src
goto main under src right click new folder
resources
goto resources folder right click new other
select xml file
hibernate.cfg.xml

open hibernate.cfg.xml file change database uid & password.


Change package name before POJO class.

3)open pom.xml
add hibernate jar file and ojdbc8 jar file
dependency to xml file

----open browser
https://mvnrepository.com/

serch hibernate core jars in website


goto Hibernate Core Relocation
select 5.6.4 final jar files
goto dependency jars copy from website
and paste in pom.xml file

again search oracle driver in mvnrepository website


search ojdbc8
goto 12.2.0.1 file
select dependency file and copy from website
paste in pom.xml file

4)goto App.java
run as Java application

Hibernate Annotation Example


------------------------------------------------------------------------------------------
Employee.java

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

<?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.Oracle
Dialect</property>
<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.username">system</property
>
<property
name="connection.password">vijay</property>

<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

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().configure(
"hibernate.cfg.xml").build();
Metadata meta = new
MetadataSources(ssr).getMetadataBuilder().b
uild();
SessionFactory factory =
meta.getSessionFactoryBuilder().build();
Session session =
factory.openSession();
Transaction t =
session.beginTransaction();
Employee e1=new Employee();
e1.setId(101);
e1.setFirstName("vijay");
e1.setLastName("kumar");
session.save(e1);
t.commit();
System.out.println("successfully
saved");
factory.close();
session.close();
}

Steps to create MAVEN Hibernate Inheritance project in Eclipse


----------------------------------------------------------------------------------
1)goto file->new->project->search MAVEN
select maven project
use default workspace location select
next
select org.apache.maven.archetypes maven-archetype-quickstart
version 1.1
next
OR
select Artifact-id :
maven-archetype-quickstart
version : 1.1
next
Group id : com.klu
Artifact id : HibernateInheritance
finish

2)expand project folder


goto src/main/java
com.klu. HibernateInheritance -->right click new class
create 4 java files
Employee.java
Contract_Employee.java
Regular_Employee.java
App.java
App.java already exist no need to create again.

goto src
goto main under src right click new folder
resources
create 2 xml files

Employee.hbm.xml

hibernate.cfg.xml

open Employee.hbm.xml file change package name.

open hibernate.cfg.xml file change database uid & password.


3)open pom.xml

add hibernate jar file and ojdbc8 jar file

dependency to xml file

----open browser

https://mvnrepository.com/

serch hibernate core jars in website

goto Hibernate Core Relocation

select 5.6.4 final jar files

goto dependency jars copy from website

and paste in pom.xml file

again search oracle driver in mvnrepository website

search ojdbc8

goto 12.2.0.1 file

select dependency file and copy from website

paste in pom.xml file

4)goto App.java
run as Java application

Hibernate Inheritance
---------------------------------------------------------------------------------

/* Employee POJO Class */

public class Employee {


private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

/* Contract_Employee Class */

public class Contract_Employee extends


Employee{
private float pay_per_hour;
private String contract_duration;
public float getPay_per_hour() {
return pay_per_hour;
}
public void setPay_per_hour(float
pay_per_hour) {
this.pay_per_hour = pay_per_hour;
}
public String getContract_duration() {
return contract_duration;
}
public void setContract_duration(String
contract_duration) {
this.contract_duration =
contract_duration;
} }
/* Regular_Employee Class */

public class Regular_Employee extends


Employee {
private float salary;
private int bonus;
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}

//Hibernate Inheritance App.java


----------------------------------------------------------------

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;

public class App


{
public static void main(String[] args)
{
Configuration cfg=new
Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf =
cfg.buildSessionFactory();
Session ss = sf.openSession();

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

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class
name="com.klu.HibernateInheritance.Employee
" table="empinh" discriminator-value="emp">
<id name="id"> <generator
class="increment"></generator> </id>
<discriminator column="type"
type="string"></discriminator>
<property name="name"></property>
<subclass
name="com.klu.HibernateInheritance.Regular_
Employee" discriminator-value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>
<subclass
name="com.klu.HibernateInheritance.Contract
_Employee" discriminator-value="con_emp">
<property name="pay_per_hour"></property>
<property
name="contract_duration"></property>
</subclass>
</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.net/
hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hbm2ddl.auto">update</property>
<property
name="dialect">org.hibernate.dialect.Oracle
Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@loc
alhost:1521:xe</property>
<property
name="connection.username">system</property
>
<property
name="connection.password">vijay</property>
<property
name="connection.driver_class">oracle.jdbc.
driver.OracleDriver</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

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>

<property name = "hibernate.dialect">


org.hibernate.dialect.MySQLDialect
</property>

<property name = "hibernate.connection.driver_class">


com.mysql.jdbc.Driver
</property>

<!-- Assume test is the database name -->

<property name = "hibernate.connection.url">


jdbc:mysql://localhost/test
</property>
<property name = "hibernate.connection.username">
root
</property>

<property name = "hibernate.connection.password">


vijay
</property>

<!-- List of XML mapping files -->


<mapping resource = "Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>

 Hibernate CRUD operations

 CRUD operations are Create(save), Read(select), Update(update) and


Delete(delete).

 Hibernate has Session interface which provides many APIs to perform


operations with database.
 ---save(Object object) Method - save() method persist the given transient
instance, first assigning a generated identifier.
 -----saveOrUpdate(Object object) Method - This method
either save(Object) or update(Object) the given instance, depending upon
the resolution of the unsaved-value checks (see the manual for a discussion
of unsaved-value checking).
 ----Session.delete(Object object) Method - Remove a persistent instance
from the datastore.
 -----Session.get() - This method returns a persistence object of the given
class with the given identifier. It will return null if there is no persistence
object.
Employee Example using Hibernate CRUD
Operations UPDATED

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>

<!-- Hibernate Properties -->


<property
name="dialect">org.hibernate.dia
lect.OracleDialect</property>
<property
name="hbm2ddl.auto">update</prop
erty>
<property
name="show_sql">true</property>

<!-- Mapping file Configuration


-->
<mapping
resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

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

public class EmployeeCreateTest {


public static void main(String[]
args) {
Configuration cfg=new
Configuration();
cfg.configure();
SessionFactory
sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Employee e=new Employee();
e.setEmpId(1020);
e.setEmpName("vijay kumar");
e.setEmpDesig("Asst. Prof");
e.setEmpSal(60000);

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

public class EmployeeUpdateTest {


public static void main(String[] args) {

Configuration cfg=new Configuration();


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

Employee e= new Employee();


e.setEmpId(1020);
e.setEmpName("kumar");
e.setEmpDesig("Assistant Professor");
e.setEmpSal(80000);

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

public class EmployeeRetrieveTestGet {


public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Object o=s.get(Employee.class, 1020);

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

public class EmployeeDeleteTest {


public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();

Employee e= new Employee();


e.setEmpId(1020);

s.delete(e);
System.out.println(e.getEmpId());
System.out.println(e);
s.beginTransaction().commit();
}
}

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy