Hibernate Interview IMP Question
1. What is hibernate ?
2. Feature of hibernate /advantage
3. Hibernate Architecture
4. What is mapping and why?
5. Different b/w hibernate and JDBC
6. What is core interface use in
hibernate
7. What is session interface?
8. What is session factory interface?
9. What is configuration interface
10. What is transaction ?
11. What is cache ?
12. What is 1st and second level cache
?/how to enable it
13.
Lazy
loading/Eager loading
14. What is generator
15. What is dialect class?
16. What is HQL
17. What’s the difference between load() and
get()?
18. What is the difference between
and merge and update
19.
what is mapping /how to use mapping in hibernate
20.
what is inheritance mapping
21.
what is relational mapping
22.
how to use join in hibernate ?
23.
what is pagination
24.
how to use prepared statement in hyb
25.
named query (provide a way to use query as meaning full
name )
26.
what dirty checking
What is hibernating?
Hibernate
is an open source and light weight Object Relational Mapping ORM Tools , it
used to map object with database .
Hibernate
run with the server or without the server so we can use hibernate for
standalone application or webapplication both
Feature of hibernate
1.
Hibernate support
inheritance/association/collection
2.
In hibernate an exception translator is given
.so it convert check exception to uncheck exception
3.
In hibernate automatically
primary key generator and it has its own query language HQL
4.
Hibernate support
cache mechanism by this number of round trip between database and application
will be reduce.
5.
Hibernate support
annotation.
6.
Hibernate support
pagination .
7.
Hibernate support
lazy loading .
8.
Hibernate provide
dialect class so we not need to write sql query
Hibernate
simplifies:
- Saving
and retrieving your domain objects
- Making
database column and table name changes
- Centralizing
pre save and post retrieve logic
- Complex
joins for retrieving related items
- Schema
creation from object model
.Why
do you need ORM tools like hibernate?
The main advantage of ORM like hibernate
is that it shields developers from messy SQL. Apart from this, ORM provides following
benefits:
- Improved
productivity
- High-level
object-oriented API
- Less Java
code to write
- No
SQL to write
- Improved
performance
- Sophisticated
caching
- Lazy
loading
- Eager
loading
- Improved
maintainability
- A
lot less code to write
- Improved
portability
10.What
are the Core interfaces are of Hibernate
framework?
·
|
The five core interfaces are
used in just about every Hibernate application. Using these interfaces, you can
store and retrieve persistent objects and control transactions.
- Configuration
interface
- Session interface
- SessionFactory
interface
- Transaction
interface
- Query and
Criteria interfaces
Session
It maintains a connection between hibernate application and
database.
It provides methods to store, update, delete or `qax fetch data from the database
such as persist(), update(), delete(), load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it
provides factory methods to return these instances.
Session
factory interface
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.
There is typically a single SessionFactory for
the whole applicationå¹¼reated during application initialization. The
SessionFactory caches generate SQL statements and other mapping metadata that
Hibernate uses at runtime. It also holds cached data that has been read in one
unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Here we can explain what is SessionFactory..
- SessionFactory is an interface, which is
available in “org.hibernate” package.
- Session
factory is long live multithreaded object.
- Usually one
session factory should be created for one database.
- When you
have multiple databases in your application you should create multiple
SessionFactory object.
- Assume the scenario that you are using
one database called mysql in your application then following is the way to
create the SessionFactory object.
Configuration cfg=new Configuration(); // Empty object will be created.
cfg=cfg.configure();
Here when you called configure() method It looks for hibernate cfg.xml and for Hibernate mapping
file.
Filled with all the properties defined in the configuration documents and mapping documents
SessionFactory sc=cfg.buildSessionFactory();
- SessionFactory object will be created
once and will be used by multiple users for long time.
- Session Factory object is the factory for
session objects.
If you are using two
databases called mysql and oracle in your hibernate application then you need to build 2 SessionFactory object
Configuration cfg=new Configuration();
Configuration cfg1=cfg.configure(“mysql.cfg.xml”);
SessionFactory sf1=cfg1.builed
SessionFactory();
Configuration
cfg2=cfg.configure(“oracle.cfg.xml”);
SessionFactory sf2=cfg2.builed
SessionFactory();
When we are using more than one database in our application than
we use the HibernateUtil class which is implemented
based on singleton
design pattern which
insure that one and only one sessionFactory object will be created for entire
application
Session factory objects are to be implemented using
the singleton design pattern. Instances
of SessionFactory are thread-safe and typically shared
throughout an application. As these objects are heavy weight because they
contains the connection information, hibernate configuration information and
mapping files,location path. So creating number of instances will make our
application heavy
weight. But the session objects are not thread safe. So in
short it is - SessionFactory objects are one per application and Session
objects are one per client.
Hence it would be one
SessionFactory per DataSource. Your application may have more than one
DataSource so you may have more than one SessionFactory in that instance. But
you would not want to create a SessionFactory more than once in an application.
What is a SessionFactory?
The SessionFactory is the concept that is a single
data store and thread safe. Because of this feature, many threads can access
this concurrently and the sessions are requested, and also the cache that is
immutable of compiled mappings for a specific database. A SessionFactory will
be built only at the time of its startup. In order to access it in the
application code, it should be wrapped in singleton. This wrapping makes the
easy accessibility to it in an application code.
Hibernate - What is a SessionFactory? - Nov 19, 2009
at 15:10 pm by Amit Satpute
What is a SessionFactory?
- SessionFactory
is an interface and extends Referenceable, Serializable
- Creates
Sessions. Usually an application has a single SessionFactory. Threads
servicing client requests obtain Sessions from the factory.
- Implementors
must be threadsafe.
- SessionFactorys
are immutable. The behaviour of a SessionFactory is controlled by
properties supplied at configuration time. These properties are defined on
Environment.
Hibernate support
cache mechanism by this number of round trip between database and application
will be reduce.
First level cache is
associated with “session” object. The scope of cache objects is of session.
Once session is closed, cached objects are gone forever. First level cache is
enabled by default and you can not disable it. When we query an entity first
time, it is retrieved from database and stored in first level cache associated
with hibernate session. If we query same object again with same session object,
it will be loaded from cache and no sql query will be executed. The loaded
entity can be removed from session using evict() method. The next loading of
this entity will again make a database call if it has been removed using
evict() method. The whole session cache can be removed using clear() method. It
will remove all the entities stored in cache.
Second level cache is
apart from first level cache which is available to be used globally in session
factory scope. second level cache is created in session factory scope and is
available to be used in all sessions which are created using that particular
session factory. It also means that once session factory is closed, all cache
associated with it die and cache manager also closed down. Whenever hibernate
session try to load an entity, the very first place it look for cached copy of
entity in first level cache (associated with particular hibernate session). If
cached copy of entity is present in first level cache, it is returned as result
of load method. If there is no cached entity in first level cache, then second
level cache is looked up for cached entity. If second level cache has cached
entity, it is returned as result of load method. But, before returning the
entity, it is stored in first level cache also so that next invocation to load
method for entity will return the entity from first level cache itself, and
there will not be need to go to second level cache again. If entity is not
found in first level cache and second level cache also, then database query is
executed and entity is stored in both cache levels, before returning as
response of load() method.
Caching
is all about application performance optimization and it sits between your
application and the database to avoid the number of database hits as many as
possible to give a better performance for performance critical applications.
Until or unless ill ask the can have lookat and have idia
Those
are all genralinfo I was saying if you put geralize information
What
date was yester day was yester day holiday I put theas gays withso he can help
him that’s think mack sence there concer
was that the don’t know enviroent
Caching
is important to Hibernate as well which utilizes a multilevel caching schemes
as explained below:
What is the difference between first level
cache and second level cache?
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.
|
·
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
issue multiple updates to an object, Hibernate tries to delay doing the update
as long as possible to reduce the number of update SQL statements issued. If
you close the session, all the objects being cached are lost and either
persisted or updated in the database.
Second-level cache:
Second
level cache is an optional cache and first-level cache will always be consulted
before any attempt is made to locate an object in the second-level cache. The
second-level cache can be configured on a per-class and per-collection basis
and mainly responsible for caching objects across sessions.
What’s the difference between load() and get()?
16.What’s the difference between load() and get()?
load() vs. get() :-
load()
|
get()
|
Only use the load() method
if you are sure that the object exists.
|
If you are not sure that the object exists, then use one of the
get()methods.
|
load() method will throw an exception
if the unique id is not found in the database. ObjectNotFoundException
|
get() method will return null if the
unique id is not found in
the database.
|
load() just returns a proxy by
default and database won’t be hit until the proxy is first invoked.
|
get() will hit the database
immediately.
|
17.What is the difference between and merge and update ?
Update() check whethere object
is already in same session or not if it find same object in session it will
throw duplicatobject exception
Use update() if
you are sure that the session does not contain an already persistent instance
with the same identifier, and merge() if
you want to merge your modifications at any time without consideration of the
state of the session.
18.How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:-
Example:-
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>
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.
Following section gives brief description of each of the class
objects involved in Hibernate Application Architecture.
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.
·
ClassMappingSetup:
This component creates the connection between the Java classes and database tables..
This component creates the connection between the Java classes and database tables..
SessionFactory Object:
Configuration object is used to create a SessionFactory object
which inturn configures Hibernate for the application using the supplied
configuration file and allows for a Session object to be instantiated. The
SessionFactory is a thread safe object and used by all the threads of an
application.
The SessionFactory is heavyweight object so usually it is created
during application start up and kept for later use. You would need one
SessionFactory object per database using a separate configuration file. So if
you are using multiple databases then you would have to create multiple
SessionFactory objects.
Session Object:
A Session is used to get a physical connection with a database.
The Session object is lightweight and designed to be instantiated each time an
interaction is needed with the database. Persistent objects are saved and
retrieved through a Session object.
The session objects should not be kept open for a long time
because they are not usually thread safe and they should be created and
destroyed them as needed.
Transaction Object:
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.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to
retrieve data from the database and create objects. A Query instance is used to
bind query parameters, limit the number of results returned by the query, and
finally to execute the query.
Criteria Object:
Criteria object are used to create and execute object oriented
criteria queries to retrieve objects.
31.What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
JDBC
|
Hibernate
|
With JDBC, developer has to write code to map an object
model's data representation to a relational data model and its corresponding database
schema.
|
Hibernate is flexible and powerful ORM solution
to map Java classes to database tables.
Hibernate itself takes care of this mapping
using XML files so developer does not need
to write code for this.
|
With JDBC, the automatic mapping of Java
objects with database tables
and vice versa conversion is to be taken care of by the developer manually
with lines of code.
|
Hibernate provides transparent persistence and developer
does not need to write code explicitly to map database tables
tuples to application objects during tuples to application
objects during interaction with RDBMS.
|
JDBC supports only native Structured
Query Language (SQL).
Developer has to find out the efficient way to access database, i.e. to
select effective query from a number of queries to perform same task.
|
Hibernate provides a powerful query
language Hibernate Query
Language (independent from type of database) that is expressed
in a
familiar SQL like syntax and includes full support for
polymorphic queries.
Hibernate also supports
native SQL statements. It also selects an
effective way to perform a database manipulation task for an
application.
|
Application using JDBC to handle persistent data (database
tables) having database specific code in large amount. The code written to
map table data to application objects and vice versa is actually to map table
fields to object properties. As table changed or database changed then it’s
essential to change object structure as well as to change code written to map
table-to-object/object-to-table.
|
Hibernate provides this mapping itself. The actual mapping
between
tables and application objects is done in XML files. If there
is change in
Database or in any table then the only need to change XML file
properties.
|
With JDBC, it is developer’s responsibility to handle JDBC
result set and convert it to Java objects through code to use this persistent
data in application. So with JDBC, mapping between Java objects and database
tables is done manually.
|
Hibernate reduces lines of code by maintaining object-table
mapping
itself and returns
result to application in form of Java objects.
It relieves programmer
from manual handling
of persistent data, hence reducing the development
time and maintenance cost.
|
With JDBC, caching is maintained by hand-coding.
|
Hibernate, with Transparent Persistence, cache is set to
application work
space. Relational tuples are moved to this
cache as a result of query. It improves performance if client
application reads same
data many times for
same write. Automatic Transparent Persistence allows the
developer to
concentrate more on business logic rather than this
application code.
|
In JDBC there is no check that always every user has updated
data. This check has to be added by the developer.
|
Hibernate enables developer to define version type field to
application,
due to this defined field Hibernate updates version field of
database
table every time
relational tuple is updated in form of Java class
object to that table. So if two users retrieve same tuple and
then
modify it and one user
save this modified tuple to database, version
is automatically
updated for this tuple by Hibernate. When other
user tries to save updated tuple to database then it does not
allow
saving it because this
user does not have updated data.
|
Persistent
The entire concept of Hibernate is to take the values from Java
class attributes and persist them to a database table. A mapping document helps
Hibernate in determining how to pull the values from the classes and map them
with table and associated fields.
Java classes whose objects or instances will be stored in database
tables are called persistent classes in Hibernate. Hibernate works best if
these classes follow some simple rules, also known as the Plain Old Java Object
(POJO) programming model. There are following main rules of persistent classes,
however, none of these rules are hard requirements.
·
All Java classes that
will be persisted need a default constructor.
·
All classes should
contain an ID in order to allow easy identification of your objects within
Hibernate and the database. This property maps to the primary key column of a
database table.
·
All attributes that
will be persisted should be declared private and have getXXX and setXXXmethods
defined in the JavaBean style.
·
A central feature of
Hibernate, proxies, depends upon the persistent class being either non-final,
or the implementation of an interface that declares all public methods.
·
All classes that do
not extend or implement some specialized classes and interfaces required by the
EJB framework.
The POJO name is used to emphasize that a given object is an
ordinary Java Object, not a special object, and in particular not an Enterprise
JavaBean.
Mapping
Many
to one Mapping :-
I've seen people use many-to-one
mappings to represent one-to-one relationships. I've also read this in a book
by Gavin King and on articles.
For example, if a customer can
have exactly one shipping address, and a shipping address can belong to only
one customer, the mapping is given as:
<class name="Customer" table="CUSTOMERS">
...
<many-to-one name="shippingAddress"
class="Address"
column="SHIPPING_ADDRESS_ID"
cascade="save-update"
unique="true"/>
...
</class>
The book reasons as (quoting it):
"You don't care what's on the target side of the association,
so you can treat it like a to-oneassociation
without the many part."
One-to-Many
Earlier in hierarchical
relationships, when beans with hierarchical
relationship exist, we created tables
with different strategies like table-per-subclass etc.
Now the other way is we will have tables with foreign key relational
associations, let us create bean classes accordingly and insert records to all
the tables.
The most unidirectional relational associations are
1. One-to-many
2. Many-to-one
3. One-to-one
4. many-to-many (with Set)
5. many-to-many (with Map)
2. Many-to-one
3. One-to-one
4. many-to-many (with Set)
5. many-to-many (with Map)
Let us discuss one by one; now the first one.
- One-To-Many Relationship: A
relationship in which each record in one table is linked (or associated)
to multiple records in another table. To talk in Java style, one object of
one Java class is related to multiple objects of another Java class. The
two tables are associated with a foreign key. The primary key of
one table is the foreign key for another table.
- Concept: One department may
contain many employees. Here, department is table dept and
employee is table employee.
- Association in tables: dept_id of dept
table is declared as foreign key in employee table.
That is, dept_id exist in both the tables.
- Bean coding: Let us
see how to implement the above association in Java classes (beans). Two
beans exist, Dept and Employee. As department
contains many employees, many Employee objects are
created and added to a java.util.Set. This set is added to Dept object.
Observe the variables of Dept
class.
private int deptId;
private String deptName;
private Set employees;
private String deptName;
private Set employees;
Dept class contains
a Set of employees. This is how foreign key representation
of tables is represented in bean classes.
After knowing this much, let us go into the programming.
Create two tables (with
following SQL commands) dept and employee and
keep ready.
SQL> create
table dept (dept_id integer, dept_name varchar(15), primary key (dept_id));
SQL> create
table employee(employee_id integer, employee_name varchar(15), dept_id integer,
primary key (employee_id), foreign key(dept_id) references dept(dept_id));
Note: "dept_id
integer" must exist as foreign key in employee
table to which data will be fed from dept table. This we do it in
mapping XML file
Now, Write the two beans.
1. File Name: Dept.java
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
|
import java.util.Set;
public class
Dept
{
private int
deptId;
private String
deptName;
private Set
employees;
public
Dept()
{
//
TODO Auto-generated constructor stub
}
public int
getDeptId()
{
return
deptId;
}
public void setDeptId(int
deptId)
{
this.deptId =
deptId;
}
public String
getDeptName()
{
return
deptName;
}
public void
setDeptName(String deptName)
{
this.deptName =
deptName;
}
public Set
getEmployees()
{
return
employees;
}
public void setEmployees(Set
employees)
{
this.employees =
employees;
}
}
|
private
Set employees;
As Dept may
contain many employees, all the employees present in the dept are
created as Set and added to Dept class. This
is how one to many association of tables is implemented in Java classes. Here
one is Dept class (represented by dept table) and many
is Employee (represented by employee table). Set is
preferred as one employee id cannot be duplicated (if duplicated, as in some
cases (one person can order the same item number of times), List can
be preferred)).
This is represented in mapping file as follows:
<class
name="Dept" table="dept">
<id
name="deptId" column="dept_id">
<generator
class="assigned"/>
</id>
<property
name="deptName" column="dept_name"
type="java.lang.String"/>
<set
name="employees" table="employee"
cascade="persist, delete">
<key
column="dept_id" />
<one-to-many
class="Employee"/>
</set>
</class>
|
set name="employees": The
value of name attribute should be the reference variable of Set declared
in Dept class (private Set employees). A novice gets confusion
here only.
The <key> element in
mapping file represents always a foreign key. Here, the foreign key is dept_id declared
in employee table. As per this foreign key dept_id, the Set elements
of Dept class are populated into employee table. This must be very clear as the
whole logic of association lies here.
cascade=”persist,
delete”
The cascade attribute
populates the data to other table records. The cascade, here, works
only for persist (inserting) and delete (deleting) operations. If cascading is
required for all the operations, write as follows:
cascade=”all”
2. File Name: Employee.java
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
|
public class
Employee
{
private int
employeeId;
private String
employeeName;
public
Employee()
{
//
TODO Auto-generated constructor stub
}
public int getEmployeeId()
{
return
employeeId;
}
public void
setEmployeeId(int employeeId)
{
this.employeeId =
employeeId;
}
public String
getEmployeeName()
{
return
employeeName;
}
public void
setEmployeeName(String employeeName)
{
this.employeeName =
employeeName;
}
}
|
3. File Name: 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">
<!-- Generated by MyEclipse
Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property
name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property
name="connection.url">
jdbc:oracle:thin:@localhost:1521:orcl1
</property>
<property
name="connection.username">scott</property>
<property
name="connection.password">tiger</property>
<property
name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property
name="myeclipse.connection.profile">
SNRaoConnection
</property>
<property
name="hbm2ddl.auto">update</property>
<property
name="show_sql">true</property>
<mapping
resource="dept.hbm.xml" />
</session-factory>
</hibernate-configuration>
|
<property
name="hbm2ddl.auto">update</property>
Actually, the above statement is not required as we have created
table manually. I prefer to have as a safety measure when a column is missed,
it is created implicitly.
4. File Name: dept.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">
<!--
This
mapping demonstrates how to map a collection <key>
to one of the primary key columns of an associated child class
with a composite key. This
is very useful for legacy data!
-->
<hibernate-mapping>
<class
name="Dept" table="dept">
<id
name="deptId" column="dept_id">s
<generator
class="assigned"/>
</id>
<property
name="deptName" column="dept_name"
type="java.lang.String"/>
<set
name="employees" table="employee"
cascade="persist, delete">
<key
column="dept_id" />
<one-to-many
class="Employee"/>
</set>
</class>
<class
name="Employee" table="employee">
<id
name="employeeId" column="employee_id">
<generator
class="assigned"/>
</id>
<property
name="employeeName" column="employee_name"
type="java.lang.String"/>
</class>
</hibernate-mapping>
|
5. Client program: Client1.java
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
|
import java.util.Set;
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class
Client1
{
public static void
main(String[] args)
{
//
TODO Auto-generated method stub
Configuration c = new
Configuration();
c.configure("/hibernate.cfg.xml");
SessionFactory sf=c.buildSessionFactory();
Session session =
sf.openSession();
Transaction trans =
session.getTransaction();
trans.begin();
//
create some Employee object
Employee emp1 = new
Employee();
emp1.setEmployeeId(1);
emp1.setEmployeeName("S
N Rao");
Employee emp2 = new
Employee();
emp2.setEmployeeId(2);
emp2.setEmployeeName("Sumathi");
Employee emp3 = new
Employee();
emp3.setEmployeeId(3);
emp3.setEmployeeName("Sasi");
Set <Employee>
emps = new HashSet<Employee>();
emps.add(emp1); // add Employee object to Set
emps.add(emp2);
emps.add(emp3);
Dept dept = new
Dept();
dept.setDeptId(1234);
dept.setDeptName("Production");
dept.setEmployees(emps); // add Set object to Dept
object
session.persist(dept);
trans.commit();
System.out.println("Records
inserted");
}
}
|
Transaction
trans = session.getTransaction();
trans.begin();
trans.begin();
The above two statements can be replaced as
Transaction
trans = session.beginTransaction();
Three Employee objects emp1, emp2 and emp3 are
created and set some values. These objects are added to Set emps. emps is
added to Dept object dept. The dept object,
at runtime, adds its own values like deptName etc. to its
own dept table and the other employeeId and employeeName etc.
to employee table.
Observe the tables output.
Following is the Console screenshot.
Now let us write one more client
program, Client2 to fetch the records of dept and employee tables
through one dept object.
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
|
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class
RetrieveClient
{
public static void
main(String args[])
{
Configuration c = new
Configuration();
c.configure("hibernate.cfg.xml");
SessionFactory sf =
c.buildSessionFactory();
Session session =
sf.openSession();
// for fetching Transaction
object is not required
Object
obj = session.get(Dept.class,
new Integer(1234));
Dept d1 = (Dept)
obj;
System.out.println(d1.getDeptId() + " " +
d1.getDeptName());
Set
mySet = d1.getEmployees();
Iterator
it = mySet.iterator();
System.out.println("\nEmployee
records:");
while(it.hasNext())
{
Employee emp = (Employee)it.next();
System.out.println(emp.getEmployeeId() + "
" + emp.getEmployeeName());
}
session.close();
System.out.println("Thank
you, One To Many is Done");
sf.close();
}
}
|
Now let us write one more client
program, DeleteClient to delete one record. When one Dept object
is deleted, it’s associated all the Employee objects are also
deleted.
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
|
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class
DeleteClient
{
public static void
main(String args[])
{
Configuration c = new
Configuration();
c.configure("hibernate.cfg.xml");
SessionFactory sf =
c.buildSessionFactory();
Session s =
sf.openSession();
Dept d1 = (Dept)
s.get(Dept.class,
new Integer(1234));
// better use load()
Transaction tx =
s.beginTransaction(); // instead of get(). Why?
s.delete(d1); //
refer separate notes on the differences of get() and load()
tx.commit();
s.close();
System.out.println("One
To Many deletion is over");
sf.close();
}
}
|
After executing the above
deletion program, check the database, the record of 1234 of dept table
and its associated records of employee table are deleted. This is the power of
Hibernate. Is it so simple in JDBC?
What are the types of
inheritance models in Hibernate?
There are three types of
inheritance models in Hibernate:
- Table per
class hierarchy
- Table per
subclass
- Table per
concrete class
Application required by hibernate
1 POJO class
2 mapping file .xml(user.hbm.xml)
3 configuration file .xml (hibernate.cfg.xml)
.What is ORM ?
ORM
stands for object/relational mapping. ORM is the automated persistence of
objects in a Java application to the tables in a relational database.
2.What does ORM consists of ?
An ORM solution consists of the
followig four pieces:
- API for
performing basic CRUD operations
- API to
express queries refering to classes
- Facilities
to specify metadata
- Optimization
facilities : dirty checking,lazy associations fetching
3.What are the ORM levels ?
The ORM levels are:
- Pure
relational (stored procedure.)
- Light
objects mapping (JDBC)
- Medium object mapping
- Full object
Mapping (composition,inheritance, polymorphism, persistence by
reachability)
·
7.What is the need for
Hibernate xml mapping file?
·
Hibernate mapping file tells
Hibernate which tables and columns to use to load and store objects. Typical
mapping file look as follows:
8) Is Session a thread-safe
object?
No, Session is not a thread-safe object, many threads can access
it simultaneously. In other words, you can share it between threads.
9) 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)
|
10) What is the difference between get and
load method?
The differences between get() and load() methods are given below.
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.
|
11) What is the difference between update and
merge method?
The differences between update() and merge() methods are given
below.
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.
|
Let's try to understand the difference by the example given below:
1.
...
2.
SessionFactory factory = cfg.buildSessionFactory();
3.
Session session1 = factory.openSession();
4.
5.
Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing id of employee
6.
session1.close();
7.
8.
e1.setSalary(70000);
9.
10. Session session2 = factory.openSession();
11. Employee e2 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing same id
12.
13. Transaction tx=session2.beginTransaction();
14. session2.merge(e1);
15.
16. tx.commit();
17. session2.close();
After closing session1, e1 is in detached state. It will not be in
session1 cache. So if you call update() method, it will throw an error.
Then, we opened another session and loaded the same Employee
instance. If we call merge in session2, changes of e1 will be merged in e2.
12) 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.
13) What are the inheritance mapping
strategies?
There are 3 ways of inheritance mapping in hibernate.
- Table per hierarchy
- Table per concrete class
- Table per subclass
14) How to make a immutable class in
hibernate?
If you mark a class as mutable="false", class will be
treated as an immutable class. By default, it is mutable="true".
15) What is automatic dirty checking in
hibernate?
The automatic dirty checking feature of hibernate, calls update
statement automatically on the objects that are modified in a transaction.
Let's understand it by the example given below:
1.
...
2.
SessionFactory factory = cfg.buildSessionFactory();
3.
Session session1 = factory.openSession();
4.
Transaction tx=session2.beginTransaction();
5.
6.
Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));
7.
8.
e1.setSalary(70000);
9.
10. tx.commit();
11. session1.close();
Here, after getting employee instance e1 and we are changing the state of e1.
After changing the state, we are committing the transaction. In
such case, state will be updated automatically. This is known as dirty checking
in hibernate.
16) How many types of association mapping are
possible in hibernate?
There can be 4 types of association mapping in hibernate.
- One to One
- One to Many
- Many to One
- Many to Many
17) Is it possible to perform collection
mapping with One-to-One and Many-to-One?
No, collection mapping can only be performed with One-to-Many and
Many-to-Many
18) What is lazy loading in hibernate?
Lazy loading in hibernate improves the performance. It loads the
child objects on demand.
Since Hibernate 3, lazy loading is enabled by default, you don't
need to do lazy="true". It means not to load the child objects when
parent is loaded.
19) What is HQL (Hibernate Query Language)?
Hibernate Query Language is known as an object oriented query
language. It is like structured query language (SQL).
The main advantage of HQL over SQL is:
- You don't need to learn SQL
- Database independent
- Simple to write query
Hibernate Query Language (HQL)
Hibernate Query Language (HQL) is same as SQL (Structured Query
Language) but it doesn't depends on the table of the database. Instead of table
name, we use class name in HQL. So it is database independent query language.
Advantage of HQL
There are many advantages of HQL. They are as follows:
- database independent
- supports polymorphic queries
- easy to learn for Java Programmer
Query Interface
It is an object oriented representation of Hibernate Query. The
object of Query can be obtained by calling the createQuery() method Session
interface.
The query interface provides many methods. There is given commonly
used methods:
- public
int executeUpdate() is used to execute the update or delete query.
- public
List list() returns the result of the ralation as a list.
- public
Query setFirstResult(int rowno) specifies the row number from where
record will be retrieved.
- public
Query setMaxResult(int rowno) specifies the no. of records to be
retrieved from the relation (table).
- public
Query setParameter(int position, Object value) it sets the value to the JDBC style query
parameter.
- public
Query setParameter(String name, Object value) it sets the value to a named query
parameter.
Example of HQL to get all the records
1.
Query query=session.createQuery("from Emp");//here persistent class name is Emp
2.
List list=query.list();
Example of HQL to get records with pagination
1.
Query query=session.createQuery("from Emp");
2.
query.setFirstResult(5);
3.
query.setMaxResult(10);
4.
List list=query.list();//will return the records from 5 to 10th number
Example of HQL update query
1.
Transaction tx=session.beginTransaction();
2.
Query q=session.createQuery("update User set name=:n where id=:i");
3.
q.setParameter("n","Udit Kumar");
4.
q.setParameter("i",111);
5.
6.
int status=q.executeUpdate();
7.
System.out.println(status);
8.
tx.commit();
Example of HQL delete query
1.
Query query=session.createQuery("delete from Emp where id=100");
2.
//specifying class name (Emp) not tablename
3.
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
1.
Query q=session.createQuery("select sum(salary) from Emp");
2.
List<Emp> list=q.list();
3.
Iterator<Emp> itr=list.iterator();
4.
while(itr.hasNext()){
5.
System.out.println(itr.next());
6.
}
Example to get maximum salary of employee
1.
Query q=session.createQuery("select max(salary) from Emp");
Example to get minimum salary of employee
1.
Query q=session.createQuery("select min(salary) from Emp");
Example to count total number of employee ID
1.
Query q=session.createQuery("select count(id) from Emp");
Example to get average salary of each employees
1.
Query q=session.createQuery("select avg(salary) from Emp");
No comments:
Post a Comment