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

Hibernate-MyNotes

Hibernate is an open-source ORM framework for Java that simplifies database interactions by mapping Java objects to database tables. It provides key components such as SessionFactory, Session, and Transaction for managing database operations and supports features like caching and HQL for database-independent queries. Hibernate is preferred over JDBC due to its lightweight nature, database independence, and ease of use without requiring extensive SQL knowledge.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Hibernate-MyNotes

Hibernate is an open-source ORM framework for Java that simplifies database interactions by mapping Java objects to database tables. It provides key components such as SessionFactory, Session, and Transaction for managing database operations and supports features like caching and HQL for database-independent queries. Hibernate is preferred over JDBC due to its lightweight nature, database independence, and ease of use without requiring extensive SQL knowledge.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 32

Hibernate Framework:

Hibernate fw is an open source, lightweight, ORM (Object Relational Mapping)


tool.
It is a programming technique that maps the object to the data stored in the
database.
The ORM tool internally uses the JDBC API to interact with the database.

Hibernate framework uses many objects confriguration, sessionfactory, session,


transaction etc.
alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java
Transaction API) and JNDI (Java Naming Directory Interface).

Main Component of Hibernate:-

SessionFactory:
The SessionFactory is a factory of session . It holds second level cache
(optional) of data.
SessionFactory interface provides factory method to get the object of Session.

Session:
The session object provides an interface between the application and data stored
in the database. It is a short-lived object.
It is factory of Transaction, Query and Criteria.
It also provides factory methods for Transaction, Query and Criteria.
Session interface provides methods to insert, update and delete the object.
It holds a first-level cache (mandatory) of data.

Transaction:
The transaction object specifies the unit of work. It is optional.
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.

*****************************

sovled :
--------

Q what is hibernate , why we use hibernate instead of jdbc?


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

ans:-

->Hibernate is an Object-Relational Mapping (ORM) solution for JAVA.


It is an open source persistent framework
Hibernate maps Java classes to database tables
Hibernate is the ORM tool given to transfer the data between a java (object)
application and a database (Relational) in the form of the objects. Hibernate is
the open source light weight tool given by Gavin King.
Hibernate is a non-invasive framework, means it wont forces the programmers to
extend/implement any class/interface, and in hibernate we have all POJO classes so
its light weight.

**instead of jdbc hibernate is better -


0-Hibernate is data base independent, your code will work for all
ORACLE,MySQL ,SQLServer etc.
Q withut writing sql it provide querys.

In case of JDBC query must be data base specific.


1. As Hibernate is set of Objects , you don?t need to learn SQL language.
You can treat TABLE as a Object .

4.You will get benefit of Cache. Hibernate support two level of cache. First level
and 2nd level. So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .

5.No need to create any connection pool in case of Hibernate. You can use c3p0.
In case of JDBC you need to write your own connection pool

Q what is orm ?
----------------
ORM is an acronym for Object/Relational mapping. It is a programming strategy to
map object with the data stored in the database. It simplifies data creation, data
manipulation and data access.
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.
A persistent framework is an ORM service that stores and retrieves objects into a
relational database.

Q Query and criteria in hibernate?


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

advantages of HQL.
database independent
supports polymorphic queries

Query Interface:-
object of Query can be obtained by calling the createQuery() method Session
interface.

Query query=session.createQuery("from Emp");//here persistent class name is Emp


List list=query.list();

HQL update query:

Transaction tx=session.beginTransaction();
Query q=session.createQuery("update User set name=:n where id=:i");
q.setParameter("n","Udit Kumar");
q.setParameter("i",111);
int status=q.executeUpdate();
System.out.println(status);
tx.commit();

Example of HQL delete query

Query query=session.createQuery("delete from Emp where id=100");


//specifying class name (Emp) not tablename
query.executeUpdate();
HQL with Aggregate functions

You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some
common examples:

Example to get total salary of all the employees

Query q=session.createQuery("select sum(salary) from Emp");


List<Integer> list=q.list();
System.out.println(list.get(0));
Example to get maximum salary of employee

Query q=session.createQuery("select max(salary) from Emp");


Example to get minimum salary of employee

Query q=session.createQuery("select min(salary) from Emp");


Example to count total number of employee ID

Query q=session.createQuery("select count(id) from Emp");


Example to get average salary of each employees

Query q=session.createQuery("select avg(salary) from Emp");

Criteria Query Language:-


------------------------
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.
programmer is able to add many criteria on a query.

Criteria Interface:-
The Criteria interface provides many methods to specify criteria.
object of Criteria can be obtained by calling the createCriteria() method of
Session interface.

Crietria c=session.createCriteria(Emp.class);//passing Class class argument

methods of Criteria interface :-


public Criteria add(Criterion c) is used to add restrictions.
public Criteria addOrder(Order o) specifies ordering.
public Criteria setFirstResult(int firstResult) specifies the first number of
record to be retreived.
public Criteria setMaxResult(int totalResult) specifies the total number of records
to be retreived.
public List list() returns list containing object.
public Criteria setProjection(Projection projection) specifies the projection
Restrictions class:-
Restrictions class provides methods that can be used as Criterion. The commonly
used methods of Restrictions class:

Order class:-
The Order class represents an order.

CQL to get all the record:


Crietria c=session.createCriteria(Emp.class);//passing Class class argument
List list=c.list();

CQL to get the 10th to 20th record


Crietria c=session.createCriteria(Emp.class);
c.setFirstResult(10);
c.setMaxResult(20);
List list=c.list();

CQL to get the records whose salary is greater than 10000


Crietria c=session.createCriteria(Emp.class);
c.add(Restrictions.gt("salary",10000));//salary is the propertyname
List list=c.list();

CQL to get the records in ascending order on the basis of salary:


Crietria c=session.createCriteria(Emp.class);
c.addOrder(Order.asc("salary"));
List list=c.list();

CQL with Projection:


We can fetch data of a particular column by projection such as name etc

ex: prints data of NAME column of the table only.


Criteria c=session.createCriteria(Emp.class);
c.setProjection(Projections.property("name"));
List list=c.list();

Q criteria - how i can select emp name wihout select id ?


----------------------------------------------------------
ans:-

Criteria c=session.createCriteria(Emp.class);
c.setProjection(Projections.property("name"));
List list=c.list();

Q how to pass data to criteria conditions dynamically binds ? how pass ?


--------------------------------------------------------------------------
ans:-
List cats = sess.createCriteria(Cat.class)
.createCriteria("kittens", "kt")
.add( Restrictions.eq("name", "F%") );

or
List sales = session.createCriteria(Sale.class)
.add(Expression.ge("date",startDate);
.add(Expression.le("date",endDate);
.addOrder( Order.asc("date") )
.setFirstResult(0)
.setMaxResults(10)
.list();
or
session.createCriteria(Sale.class)
.add(Expression.lt("date",salesDate))
.list();

session.createCriteria(Sale.class)
.add(Expression.eq("product",someProduct))
.list();

or

hibernateCriteria = hibernateCriteria.add(eq(element, fieldValue));

hibernateCriteria = hibernateCriteria.createCriteria(element);

Q what is sessionfactory in hibernate ?


-----------------------------------------
SessionFactory:
The SessionFactory is a factory of session ,
It holds second level cache (optional) of data. SessionFactory interface provides
factory method to get the object of Session.
The SessionFactory is a thread safe object and used by all the threads of an
application.
one SessionFactory object per database using a separate configuration file.
Configuration object is used to create a SessionFactory object.

//creating seession factory object


SessionFactory factory=cfg.buildSessionFactory();

Session Object :-
Session
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.
It maintains a connection between hibernate application and database.
It provides methods to store, update, delete or fetch data from the database such
as persist(), update(), delete(), load(), get() etc.
//creating session object
Session session=factory.openSession();

Q Difference between HQL and Criteria Query in Hibernate ?


------------------------------------------------------------
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 is suitable for executing Static Queries, where as Criteria is suitable for
executing Dynamic Queries
HQL doesn�t support pagination concept, but we can achieve pagination with Criteria
Criteria used to take more time to execute then HQL
With Criteria we are safe with SQL Injection because of its dynamic query
generation but in HQL as your queries are either fixed or parametrized, there is no
safe from SQL Injection.

Q how to manage session in hibernate ?


---------------------------------------
ans:-

Hibernate Sessions
Sessions are a Hibernate construct used to mediate connections with the database.
The session opens a single database connection when it is created, and holds onto
it until the session is closed. Every object that is loaded by Hibernate from the
database is associated with the session, allowing Hibernate to automatically
persist objects that are modified, and allowing Hibernate to implement
functionality such as lazy-loading.

Best way to manage Transaction in Hibernate is to use HibernateTemplate .

HibernateTemplate provides you a functionality where session lifecycle is


automatically managed .session will be automatically closed without explicitely
calling session.close () .

The best is to manage a hibernate session is to open a new session for every
request.

if you use sessionFactory.getCurrentSession(), you'll obtain a "current session"


which is bound to the lifecycle of the transaction and will be automatically
flushed and closed when the transaction ends (commit or rollback)
if you decide to use sessionFactory.openSession(), you'll have to manage the
session yourself and to flush and close it "manually".

The best is to manage a hibernate session is to open a new session for every
request. It all depends on how you obtain the session.

if you use sessionFactory.getCurrentSession(), you'll obtain a "current session"


which is bound to the lifecycle of the transaction and will be automatically
flushed and closed when the transaction ends (commit or rollback)
if you decide to use sessionFactory.openSession(), you'll have to manage the
session yourself and to flush and close it "manually".

---------------
Q What is the difference between session.save() and session.persist() method?

No. save() persist()


1) returns the identifier (Serializable) of the instance. return
nothing because its return type is void.
2) Syn: public Serializable save(Object o) Syn: public void
persist(Object o)

Q what is diff get and load in hibernate ? [imp]


--------------------------------------------
ans:-
No. get() load()
1) Returns null if object is not found. Throws ObjectNotFoundException if
object is not found.

2) get() method always hit the database. load() method doesn't hit the
database.

3) It returns real object not proxy. It returns proxy object.

4) It should be used if you are not sure about the existence of instance.
It should be used if you are sure that instance
exists.

Q What is the difference between update and merge method?


----------------------------------------------------------
No. update() method merge() method
1) Update means to edit something. Merge means to combine something.

2) update() should be used if session doesn't contain an already persistent


state with same id.
It means update should be used inside the session only. After closing the
session it will throw error.
merge() should be used if you don't know the
state of the session, means you
want to make modification at any time.

Q What are the states of object in hibernate?


---------------------------------------------
There are 3 states of object (instance) in hibernate.

Transient: The object is in transient state if it is just created but has no


primary key (identifier) and not associated with session.
Persistent: The object is in persistent state if session is open, and you just
saved the instance in the database or retrieved the instance from the database.
Detached: The object is in detached state if session is closed. After detached
state, object comes to persistent state if you call lock() or update() method.
Q what are the cache in hibernate ? who use to first level cache and second level
cache ?
-----------------------------------------------------------------------------------
--------
or
Q two cache [first and second level]in hibernate ? cache [providers] name?
-----------------------------------------------------------------------------
ans:
Cache memory stores recently used data items in order to reduce the number of
database hits as much as possible.

First-level Cache:- [client -> session ----> (first cache) ----database ]


Hibernate uses first-level cache by default and you have nothing to do to use
first-level cache.
The first-level cache is the Session cache and is a mandatory cache through which
all requests must pass. The Session object keeps an object under its own power
before committing it to the database.
If you close the session, all the objects being cached are lost and either
persisted or updated in the database.

The Second Level Cache:

The Hibernate second-level cache is set up in two steps.


First, you have to decide concurrency strategy to use.
After that, configure cache expiration and physical cache attributes using
the cache provider.

Cache Provider:
1 EHCache
It can cache in memory or on disk and clustered caching and it supports the
optional Hibernate query result cache.

2 OSCache
3 warmCache
4 JBoss Cache

steps 1

Note:-You will specify a cache provider in hibernate.cfg.xml configuration file. We


choose EHCache as our second-level cache provider:
ex:
<!-- Assume students 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">
root123
</property>
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>

step 2:
you need to specify the properties of the cache regions. EHCache has its own
configuration file, ehcache.xml, which should be in the CLASSPATH of the
application. A cache configuration in ehcache.xml for the Employee class may look
like this:
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="Employee"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>

or

Hibernat Cache :
Hibernate caching improves the performance of the application by pooling the object
in the cache.

There are mainly two types of caching: first level cache and second level cache.

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

Second Level Cache

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.

Second Level Cache implementations are provided by different vendors such as:
Hibernate second level cache uses a common cache for all the session object of a
session factory. It is useful if you have multiple session objects from a session
factory.

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.

EH Cache
OS Cache
Swarm Cache
JBoss Cache
Each implementation provides different cache usage functionality. There are four
ways to use second level cache.
read-only: caching will work for read only operation.
nonstrict-read-write: caching will work for read and write but one at a time.
read-write: caching will work for read and write, can be used simultaneously.
transactional: caching will work for transaction.
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:

<cache usage="read-only" />


Let's see the second level cache implementation and cache usage.

Implementation read-only nonstrict-read-write read-write transactional


EH Cache Yes Yes Yes No

3 extra steps for second level cache example using EH cache

1) Add 2 configuration setting in hibernate.cfg.xml file

<property
name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>

2) Add cache usage setting in hbm file

<cache usage="read-only" />


3) Create ehcache.xml file

<?xml version="1.0"?>
<ehcache>

<defaultCache
maxElementsInMemory="100"
eternal="true"/>

</ehcache>

Q can i disable second level cache ?


-------------------------------------
yes- we can disable.

Q What is the difference between first level cache and second level cache?
---------------------------------------------------------------------------
ans
No. First Level Cache Second Level Cache
1) First Level Cache is associated with Session. Second Level Cache is
associated with SessionFactory.
2) It is enabled by default. It is not enabled by default.

Q give a many to many example ?


---------------------------------
Example:
Let us see this, if we apply many to many association between two pojo class
objects student and course, provided the relationship is one student may joined in
multiple courses and one course contains lot of students (joined by multiple
students)
Remember, when ever we are applying many to many relationship between two pojo
class objects, on both sides we need a collection property [As we are applying one
to many from both the sides]
Note Points:
While applying many to many relationship between pojo classes, a mediator table is
mandatory in the database, to store primary key as foreign key both sides, we call
this table as Join table
In many to many relationship join table contain foreign keys only
Many To Many Relationship Example
files required�..
Student.java
Course.java
Course.hbm.xml
Student.hbm.xml
OurLogic.java
hibernate.cfg.xml
Student.java

package str;

import java.util.Set;

public class Student {

private int studentId;


private String studentName;
private int marks;

private Set courses;

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


this.studentName = studentName;
}

public int getMarks() {


return marks;
}

public void setMarks(int marks) {


this.marks = marks;
}

public Set getCourses() {


return courses;
}

public void setCourses(Set courses) {


this.courses = courses;
}

package str;

import java.util.Set;

public class Student {

private int studentId;


private String studentName;
private int marks;

private Set courses;

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


this.studentName = studentName;
}

public int getMarks() {


return marks;
}

public void setMarks(int marks) {


this.marks = marks;
}

public Set getCourses() {


return courses;
}

public void setCourses(Set courses) {


this.courses = courses;
}

}
Course.java

package str;

import java.util.Set;
public class Course {

private int courseId;


private String courseName;
private int duration;

private Set students;

public int getCourseId() {


return courseId;
}

public void setCourseId(int courseId) {


this.courseId = courseId;
}

public String getCourseName() {


return courseName;
}

public void setCourseName(String courseName) {


this.courseName = courseName;
}

public int getDuration() {


return duration;
}

public void setDuration(int duration) {


this.duration = duration;
}

public Set getStudents() {


return students;
}

public void setStudents(Set students) {


this.students = students;
}

package str;

import java.util.Set;

public class Course {

private int courseId;


private String courseName;
private int duration;

private Set students;

public int getCourseId() {


return courseId;
}

public void setCourseId(int courseId) {


this.courseId = courseId;
}

public String getCourseName() {


return courseName;
}

public void setCourseName(String courseName) {


this.courseName = courseName;
}

public int getDuration() {


return duration;
}

public void setDuration(int duration) {


this.duration = duration;
}

public Set getStudents() {


return students;
}

public void setStudents(Set students) {


this.students = students;
}

}
Student.hbm.xml

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

<hibernate-mapping>
<class name="str.Student" table="student">

<id name="studentId" column="studentid" />

<property name="studentName" column="studentname" length="20"/>


<property name="marks" />

<set name="courses" cascade="all" table="students_courses">

<key column="student_id "/>


<many-to-many class="str.Course" column="course_id" />

</set>

</class>

</hibernate-mapping>

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="str.Student" table="student">

<id name="studentId" column="studentid" />

<property name="studentName" column="studentname" length="20"/>


<property name="marks" />

<set name="courses" cascade="all" table="students_courses">

<key column="student_id "/>


<many-to-many class="str.Course" column="course_id" />

</set>

</class>

</hibernate-mapping>
Course.hbm.xml

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

<hibernate-mapping>
<class name="str.Course" table="courses">

<id name="courseId" column="courseid" />

<property name="courseName" column="coursename" length="20"/>


<property name="duration" />

<set name="students" inverse="false" cascade="all" table="students_courses">

<key column="course_id" />


<many-to-many class="str.Student" column="student_id "/>

</set>

</class>

</hibernate-mapping>

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

<hibernate-mapping>
<class name="str.Course" table="courses">

<id name="courseId" column="courseid" />

<property name="courseName" column="coursename" length="20"/>


<property name="duration" />

<set name="students" inverse="false" cascade="all" table="students_courses">


<key column="course_id" />
<many-to-many class="str.Student" column="student_id "/>

</set>

</class>

</hibernate-mapping>
OurLogic.java

package str;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class OurLogic {

public static void main(String args[])


{

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();

Student s1=new Student();


s1.setStudentId(100);
s1.setStudentName("James");
s1.setMarks(98);

Student s2=new Student();


s2.setStudentId(101);
s2.setStudentName("Lee");
s2.setMarks(99);

Course c1=new Course();


c1.setCourseId(500);
c1.setCourseName("Hibernate");
c1.setDuration(7);

Course c2=new Course();


c2.setCourseId(501);
c2.setCourseName("Java");
c2.setDuration(30);

Set s =new HashSet();


s.add(c1);
s.add(c2);

s1.setCourses(s);
s2.setCourses(s);

Transaction tx = session.beginTransaction();
session.save(s1);
session.save(s2);

tx.commit();

session.close();
System.out.println("Many To Many Bi-Directional is Done..!!");
factory.close();

}
}

package str;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class OurLogic {

public static void main(String args[])


{

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();

Student s1=new Student();


s1.setStudentId(100);
s1.setStudentName("James");
s1.setMarks(98);

Student s2=new Student();


s2.setStudentId(101);
s2.setStudentName("Lee");
s2.setMarks(99);

Course c1=new Course();


c1.setCourseId(500);
c1.setCourseName("Hibernate");
c1.setDuration(7);

Course c2=new Course();


c2.setCourseId(501);
c2.setCourseName("Java");
c2.setDuration(30);

Set s =new HashSet();


s.add(c1);
s.add(c2);

s1.setCourses(s);
s2.setCourses(s);

Transaction tx = session.beginTransaction();

session.save(s1);
session.save(s2);

tx.commit();

session.close();
System.out.println("Many To Many Bi-Directional is Done..!!");
factory.close();

}
}
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="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

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

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

<?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="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

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

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

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

Q can i map more than object class with database table? [many to one]
----------------------------------------------------------------------
In the many to one relationship, the relationship is applied from child object to
parent object, but in one to may parent object to child object right..! just
remember
many to one is similar to one to many but with the little changes
If we want to apply many to one relationship between two pojo class objects then
the following changes are required
In the child pojo class, create an additional property of type parent for storing
the parent object in child object [ If you are confused just remember you will be
able to understand in the example ], in the child pojo class mapping file we need
to write <many-to-one name=��> for parent type property unlike <property name=��>
Example on Many to One With Insert Query
files required�
Vendor [parent pojo]
Customer.java [child pojo]
OurLogic.java [our logic]
Vendor.hbm.xml
Customer.hbm.xml
hibernate.cfg.xml
Vendor.java

package str;

public class Vendor {

private int vendorId;


private String vendorName;

public int getVendorId() {


return vendorId;
}
public void setVendorId(int vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package str;

public class Vendor {

private int vendorId;


private String vendorName;

public int getVendorId() {


return vendorId;
}
public void setVendorId(int vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}

}
Customer.java

package str;
public class Customer {

private int customerId;


private String customerName;
private Vendor parentObjects;

public Vendor getParentObjects() {


return parentObjects;
}
public void setParentObjects(Vendor parentObjects) {
this.parentObjects = parentObjects;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package str;
public class Customer {

private int customerId;


private String customerName;
private Vendor parentObjects;

public Vendor getParentObjects() {


return parentObjects;
}
public void setParentObjects(Vendor parentObjects) {
this.parentObjects = parentObjects;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
Vendor.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="str.Vendor" table="vendor">

<id name="vendorId" column="vendid" />


<property name="vendorName" column="vendname" length="10"/>

</class>
</hibernate-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="str.Vendor" table="vendor">

<id name="vendorId" column="vendid" />


<property name="vendorName" column="vendname" length="10"/>

</class>
</hibernate-mapping>
Customer.hbm.xml

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

<hibernate-mapping>
<class name="str.Customer" table="customer">

<id name="customerId" column="custid" />


<property name="customerName" column="custname" length="10"/>
<many-to-one name="parentObjects" column="Vdummy" class="str.Vendor"
cascade="all" />

</class>
</hibernate-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="str.Customer" table="customer">

<id name="customerId" column="custid" />


<property name="customerName" column="custname" length="10"/>
<many-to-one name="parentObjects" column="Vdummy" class="str.Vendor"
cascade="all" />

</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="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

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

<mapping resource="Customer.hbm.xml"></mapping>
<mapping resource="Vendor.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

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

<mapping resource="Customer.hbm.xml"></mapping>
<mapping resource="Vendor.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
OurLogic.java

package str;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class OurLogic {

public static void main(String args[])


{

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();

Vendor v =new Vendor();

v.setVendorId(101);
v.setVendorName("java4s");

Customer c1=new Customer();

c1.setCustomerId(504);
c1.setCustomerName("customer4");
c1.setParentObjects(v);
Customer c2=new Customer();

c2.setCustomerId(505);
c2.setCustomerName("customer5");
c2.setParentObjects(v);

Customer c3=new Customer();

c3.setCustomerId(506);
c3.setCustomerName("customer6");
c3.setParentObjects(v);

Transaction tx = session.beginTransaction();

session.save(c1);
session.save(c2);
session.save(c3);

tx.commit();
session.close();
System.out.println("One To Many is Done..!!");
factory.close();

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package str;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class OurLogic {

public static void main(String args[])


{

Configuration cfg = new Configuration();


cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();

Vendor v =new Vendor();

v.setVendorId(101);
v.setVendorName("java4s");

Customer c1=new Customer();

c1.setCustomerId(504);
c1.setCustomerName("customer4");
c1.setParentObjects(v);

Customer c2=new Customer();

c2.setCustomerId(505);
c2.setCustomerName("customer5");
c2.setParentObjects(v);

Customer c3=new Customer();

c3.setCustomerId(506);
c3.setCustomerName("customer6");
c3.setParentObjects(v);

Transaction tx = session.beginTransaction();

session.save(c1);
session.save(c2);
session.save(c3);

tx.commit();
session.close();
System.out.println("One To Many is Done..!!");
factory.close();

}
}
Notes:
In line numbers 28,34,40 we are adding parent to child object
In line number 44,45,46 we are saving all child objects, but you know some thing,
according to this code at line number 45, first child object will be saved with the
parent, at 45,46 just child (customer object) only will be saved as parent is
saved alread

Q hibernate state ? tell all states in hibernate ?


or
Hibernate Lifecycle Of pojo Class Objects/entity ?
-----------------------------------------------------
Transient state
Persistent state
Detached state

Transient & Persistent states:


When ever an object of a pojo class is created then it will be in the Transient
state
When the object is in a Transient state it doesn�t represent any row of the
database, i mean not associated with any Session object, if we speak more we can
say no relation with the database its just an normal object
If we modify the data of a pojo class object, when it is in transient state then it
doesn�t effect on the database table
When the object is in persistent state, then it represent one row of the database,
if the object is in persistent state then it is associated with the unique Session
if we want to move an object from persistent to detached state, we need to do
either closing that session or need to clear the cache of the session
if we want to move an object from persistent state into transient state then we
need to delete that object permanently from the database

If we want to save an object into database then we need to call any one of the
following 3 methods
save()
persist()
saveOrUpdate()
i will explain about persist, saveOrUpdate methods later�.
If we want to load an object from database, then we need to call either load() or
get() methods
Transient:
One newly created object,with out having any relation with the database, means
never persistent, not associated with any Session object
Persistent:
Having the relation with the database, associated with a unique Session object
Detached:
previously having relation with the database [persistent ], now not associated with
any Session
see the next sessions for the better understanding of the life cycle states of pojo
class object(s) the hibernate

or

A new instance of a a persistent class which is not associated with a Session, has
no representation in the database and no identifier value is considered transient
by Hibernate:

Person person = new Person();


person.setName("Foobar");
// person is in a transient state

A persistent instance has a representation in the database, an identifier value and


is associated with a Session. You can make a transient instance persistent by
associating it with a Session:

Long id = (Long) session.save(person);


// person is now in a persistent state

Now, if we close the Hibernate Session, the persistent instance will become a
detached instance: it isn't attached to a Session anymore (but can still be
modified and reattached to a new Session later though)

or

Transient State

All objects start off in the transientstate


� Account account = new Account();
� account is a transient object
Hibernate is not aware of the object instance.
Not related to database row
No value for accountId.
Garbage collected when no longer referenced by any other objects

Persistent State

Hibernate is aware of, and managing, the object Has a database id


Already existing object retrieved from the database
Formerly transient object about to be saved
This is the only state where objects are saved to the database
Modifications made in other states are NOT saved to the database while the object
remains in that state
Changes to objects in a persistent state are automatically saved to the database
without invoking session persistence methods
Objects are made persistent through calls against the Hibernate session
� session.save(account); � session.lock(account);
� session.update(account); � session.merge(account);
Session session = SessionFactory.getCurrentSession();
// �transient� state � Hibernate is NOT aware that it exists
Account account = new Account();
// transition to the �persistent� state. Hibernate is NOW
// aware of the object and will save it to the database
session.saveOrUpdate(account);
// modification of the object will automatically be
// saved because the object is in the �persistent� state
account.setBalance(500);
// commit the transaction
session.getTransaction().commit();

Removed State

A previously persistent object that is deleted from the database


� session.delete(account);
Java instance may still exist, but it is ignored by Hibernate
� Any changes made to the object are not saved to
the database
� Picked up for garbage collection once it falls out
of scope
� Hibernate does not null-out the in-memory object

Session session = SessionFactory.getCurrentSession();


// retrieve account with id 1. account is returned in a �persistent� state
Account account = session.get(Account.class, 1);
// transition to the �removed� state. Hibernate deletes the
// database record, and no longer manages the object
session.delete(account);
// modification is ignored by Hibernate since it is in the �removed� state
account.setBalance(500);
// commit the transaction
session.getTransaction().commit();
// notice the Java object is still alive, though deleted from the database.
// stays alive until developer sets to null, or goes out of scope
account.setBalance(1000);

Detached State

A persistent object that is still referenced after closure of the active session
� session.close() changes object�s state from persisted to detached
Still represents a valid row in the database
No longer managed by Hibernate
Changes made to detached objects are not saved to the database while object remains
in the detached state
Can be reattached, returning it to the persistent state and causing it to save its
state to the database
update();
merge();
lock(); // reattaches, but does not save state
Session session1 = SessionFactory.getCurrentSession();
// retrieve account with id 1. account is returned in a �persistent� state
Account account = session1.get(Account.class, 1);
// transition to the �detached� state. Hibernate no longer manages the object
session1.close();
// modification is ignored by Hibernate since it is in the �detached�
// state, but the account still represents a row in the database
account.setBalance(500);
// re-attach the object to an open session, returning it to the �persistent�
// state and allowing its changes to be saved to the database
Session session2 = SessionFactory.getCurrentSession();
session2.update(account);
// commit the transaction
session2.getTransaction().commit();

Q what is transaction ? for what purpose we used this ? and how to start
transaction ?
-----------------------------------------------------------------------------------
----
ans:-

The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
A Transaction represents a unit of work with the database and most of the RDBMS
supports transaction functionality. Transactions in Hibernate are handled by an
underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this
interface, instead managing transactions in their own application code.

================================================** SQL QUERYS


**==================================

Q query for 2nd heighest salary ?


----------------------------------
ans:
2nd heighest:
SELECT name, MAX(salary) AS salary FROM employee WHERE salary < (SELECT MAX(salary)
FROM employee);
or
SELECT max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary) FROM
Employee);

How to find the third largest salary:


SELECT name, MAX(salary) AS salary FROM employee WHERE salary < (SELECT MAX(salary)
FROM employee WHERE salary < (SELECT MAX(salary)

FROM employee));

Q sql query to select all emp of perticular dept and table are 2 emp , dept ?
------------------------------------------------------------------------------
note -> if perticular dept then use where or having
else
ex: 1
----------
java 10
php 8
.net 6

select count(e.empno), d.deptno, d.dname


from emp e, dep d
where e.DEPTNO = d.DEPTNO
group by d.deptno, d.dname;

Highest Salary in each department


SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID

7)Display the names of all the employees who are


working in depart
number 10.
a)select emame from emp where deptno=10;

8)Display the names of all the employees who are


working as clerks and
drawing a salary more than 3000.
a)select ename from emp where job='CLERKS'
and sal>3000;

country wise cust:


SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

Q joins in hibernate ?
----------------------
ans:
Hibernate supports 4 types of joins..

Left Join: returns all rows from the left table, even if there are no matches in
the right table.

Right Join : returns all rows from the right table, even if there are no matches
in the left table.

Full Join: returns rows when there is a match in one of the tables.

Inner Join : returns rows when there is a match in both tables.

the DEFAULT join in hibernate is Inner join

Q diff bw truncate and delete ?


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

The DELETE
command is used to remove some or all rows from a table. A WHERE clause can be used
to only remove some rows. If no WHERE condition is specified, all rows will be
removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the
transaction to make the change permanent or to undo it. Note that this operation
will cause all DELETE triggers on the table to fire

TRUNCATE
removes all rows from a table. The operation cannot be rolled back and no triggers
will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a
DELETE.

The DROP
command removes a table from the database. All the tables' rows, indexes and
privileges will also be removed. No DML triggers will be fired. The operation
cannot be rolled back.

Q Basic Difference bw function and procedur ?


---------------------------------------------
ans:-
Function must return a value but in Stored Procedure it is optional (Procedure can
return zero or n values).
Functions can have only input parameters for it whereas Procedures can have
input/output parameters .
Functions can be called from Procedure whereas Procedures cannot be called from
Function.

You might also like