Hibernate-MyNotes
Hibernate-MyNotes
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 :
--------
ans:-
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.
advantages of HQL.
database independent
supports polymorphic queries
Query Interface:-
object of Query can be obtained by calling the createQuery() method Session
interface.
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();
You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some
common examples:
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.
Order class:-
The Order class represents an order.
Criteria c=session.createCriteria(Emp.class);
c.setProjection(Projections.property("name"));
List list=c.list();
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.createCriteria(element);
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();
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.
The best is to manage a hibernate session is to open a new session for every
request.
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.
---------------
Q What is the difference between session.save() and session.persist() method?
2) get() method always hit the database. load() method doesn't hit the
database.
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.
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
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.
Session object holds the first level cache data. It is enabled by default. The
first level cache data will not be available to entire application. An application
can use many session object.
SessionFactory object holds the second level cache data. The data stored in the
second level cache will be available to entire application. But we need to enable
it explicitely.
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.
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:
<property
name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<?xml version="1.0"?>
<ehcache>
<defaultCache
maxElementsInMemory="100"
eternal="true"/>
</ehcache>
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.
package str;
import java.util.Set;
package str;
import java.util.Set;
}
Course.java
package str;
import java.util.Set;
public class Course {
package str;
import java.util.Set;
}
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">
</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">
</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">
</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">
</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;
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;
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
<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>
<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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package str;
}
Customer.java
package str;
public class Customer {
<?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">
</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">
</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">
</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">
</class>
</hibernate-mapping>
hibernate.cfg.xml
<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;
v.setVendorId(101);
v.setVendorName("java4s");
c1.setCustomerId(504);
c1.setCustomerName("customer4");
c1.setParentObjects(v);
Customer c2=new Customer();
c2.setCustomerId(505);
c2.setCustomerName("customer5");
c2.setParentObjects(v);
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;
v.setVendorId(101);
v.setVendorName("java4s");
c1.setCustomerId(504);
c1.setCustomerName("customer4");
c1.setParentObjects(v);
c2.setCustomerId(505);
c2.setCustomerName("customer5");
c2.setParentObjects(v);
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
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:
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
Persistent State
Removed State
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.
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
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.
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.