Sie sind auf Seite 1von 78

What is an ORM tool and benefits of it

• ORM tool – Programming technique to map


object to the data stored in the DB.
• Hibernate is ORM tool that simplifies the
development of java application to interact
with DB.
Benefits of hibernate
• Open source and lightweight
• Fast performance-Using caching mechanism
• Database independent query-HQL works with any
DB. If DB is changed there is no change in the
HQL queries.
• Inheritance
• Associations - One-To-One, One-To-Many, Many-
To-One, Many-to-Many
• Collections - List, Set, Map, Bag
• Change of DB is easy by changing the dialect.
What is Lazy loading and eagerly
loading?
Lazy loading
• Desn’t load the the child object unless it is
explicitly asked for. ex:getEmployees()
• It is the default type of fetch.
• Ex:@OneToMany(fetch = FetchType.LAZY)
Eager loading
• Loads all the child objects with parent
• Ex:@OneToMany(fetch = FetchType.EAGER)
What is N+1 problem? How will you
handle that?
The problem comes with one-to-many relationship.
Consider Department and Employee object (relationship one-to-many)
Each Department has many employees
Problem:
-CreateQuery(from department)
-get the list of department ,iterate each department, get the list of employees for each department
SQL looks like
-- To Get all Departments
SELECT * FROM Department;-------------1 select statement for Department

-- To get each Employee, get Employee details-----------N number of select statements for Employee

SELECT * FROM Employee WHERE Employee.departmentId = ?


SELECT * FROM Employee WHERE Employee.departmentId = ? ,…

Select query runs for N number of department


Ex: If there are 20 departments , 20 select queries will be executed for getting employees
What is N+1 problem? How will you
handle that?
Solution for Hibernate N+1 Problem
Solution:
There are 2 ways to do.
1) @Fetch(FetchMode.SUBSELECT)
It does the fetching using subquery (single query)
select *From employee where departmentid in (select departmentid from department)

2)Set the batch size


@BatchSize(size=10)(it tells how many collections to be loaded)
If you have 20 department , reduce the 20 select query to 2 select query by select In statement to per-
fetch.

select *From employee where departmentid in(?,?,?,?,?,?,?,?,?,?)


select *From employee where departmentid in(?,?,?,?,?,?,?,?,?,?)

@OneToMany(mappedBy="department",fetch=FetchType.LAZY)
@BatchSize(size=10)
private List<Employee> listEmployee;
In one-to-many if you want to remove
duplicates, how will you do that?
• Use SET instead of list.
• Hibernate automatically includes distinct with
query
Hibernate Caching - Is First Level Cache
By Default Enabled??
• Yes, And we can’t disable it.
• First level cache is associated with “session”
object so it is called as Session Level Cache.
• The scope of cache objects is within session.
Once session is closed, cached objects are
gone forever.
Get vs Load()
Load
• It won’t hit the db immediately instead it creates proxy class of
student with id field.
Ex:Student stud=Session.load(Student.class,new Integer(100);
• When you try to get or set any data from Student object
Ex:stud.getName()-will hit the db retrieve the value.
If the row is not present at db it throws ObjectNotFoundException
GET
• Immediately it hits the db and retrieve the row.
• If the row is not present in DB return NULL not the exception
Student stud=Session.get(Student.class,new Integer(100);
save and persistance
Save
• Return serializable object
Persist
• Won’t return anything(void)
How will u call procedure in Hibernate
• session.createSQLQuery(“ CALL
GetEmployees(:employeeID)”)
.addEntity(Employee.class)
.setParameter(“employeeID”,100);
• @NamedNativeQueries({
@NamedNativeQuery(
name=“callGetEmployeeProcedure”,
query=“CALL GetEmployees(:employeeID)”,
resultClass=Employee.class)})
what are all the interfaces used in
hibernate?
• Configuration interface
• Transaction interface
• SessionFactory interface
• Session interface
• Query and Criteria interface
Is session factory is ThreadSafe?
• SessionFactory is thread safe.
• Session is not thread safe.
when do we go for named query and
hql
Named query
• The Hibernate framework provides the concept of named queries so that
application programmer need not to scatter queries to all the java
code,have the all queries in one place with name.
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
Query query = session.getNamedQuery("findEmployeeByName");
query.setString("name", “vino");
How to specify two primary key
columns in java entity class
For composite primary key –JPA specifies special id class

EX:
@Entity
@IdClass(ProjectId.Class)
Class Project
{
@id int departmentid;
@id int projected;
}

Class ProjectId
{
int departmentid;
int projectId;
}
Embedded primary key
@Entity
Class Project
{
@EmbeddedId ProjectId id;
}
@Embeddable
Class ProjectId
{
int departmentid;
int projectId;
}
consider a dataset (Structured data).
By using collections mechanisams can
you split it?
• Using List.sublist();
How transaction is happening via
hibernate?
• Session creates physical connection with DB
• And a transaction is instantiated by
calling Transaction t=session.beginTransaction()
• t.begin()
• Write queries to execute.
• t.commit()
• If exception occurs t.rollback()
What is optimistic locking? How to
implement it in hibernate? or it will
internally maintained by hibernate API
Optimistic
• Transaction allowed without locking the data source.
• Before committing each transaction verifies that no
other transaction has modified its data.
• If the check reveals conflicting modifications, the
committing transaction rolls back
@Version
@Column(name="OPTLOCK")
public Integer getVersion()
In hibernate if there are two users
updating a same table in a database
?.How hibernate will handle this?
• By locking mechanism
HQL vs Native SQL - which is better
• With native SQL application loses the portability from one database
to another
• HQL return object,even child objects are as part of query result
• It has pagination,dynamic profiling
• It includes all OOPs concepts
• SQL is based on a relational database model whereas HQL is a
combination of object-oriented programming with relational
database concepts.
• SQL manipulates data stored in tables and modifies its rows and
columns. HQL is concerned about objects and its properties.
• SQL is concerned about the relationship that exists between two
tables while HQL considers the relation between two objects.
how will you write complex queries in
hibernate
• Using HQL and Criteria Joins.
How to configure Hibernate in an
application.
• Add the jar necessary jar files
• Add hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver </property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost/test </property>
<property
name="hibernate.connection.username">
root </property>
<property
name="hibernate.connection.password">
root123 </property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
what is session and session factory?
• sessionFactory-factory class to create session
object ,only one per application.
• It is thread safe.
• Session-creates physical DB connection for
transaction, use as many sessions for
transactions.
Object states in hibernate?
• Transient state
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(“Vino");
• Persistent state
You can make a transient instance persistent by associating it with
a Session
session.save(person);
• Detached state
it doen’t attached to a Session,if session is closed
What is named query
• Grouping the queries at one place with name, instead of having it in each
method.
• Declaration
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)

Query query = session.getNamedQuery("findEmployeeByName");


query.setString("name", “Test");
What is data source?
• Connection provider or data
base(Oracle,MySql)
Our organization has change the DB
from oracle to sql server so where I
need to change the code without
impact the appl’n.
• In hibernate.cfg.xml file
• <property name="hibernate.dialect">
org.hibernate.dialect.SQLServer2008Dialect
</property>
What is dialect in hibernate?
• Used to configure database connected
• <property
name="hibernate.dialect">org.hibernate.diale
ct.Oracle10gDialect
</property>
What is HQL How u wil implement the
HQL..AND structure
• HQL is Hibernate provided Query Language.
• It build the query based on the Entity class
and properties.
• It is database independent language.
Structure:-
" SELECT ref.attribute FROM ClassName ref“
Ex:-
String hql=“SELECT E.firstName FROM Employee E“;
Query query = session.createQuery(hql);
What is Hibernate Criteria.
How is hibernate communicates with
database
• Using Session Object
What is cascade in Hibernate
• Cascading is Hibernate's way of useing transitive persistence
model. Transitive persistence is a technique that allows you to
propagate persistence to transient( object not yet saved in
database) and detached subgraphs( child objects)
automatically
• Cascading is a process of doing operation on parent
automatically reflects on child objects also.
• Here operation means save-update, delete, all-delete-orphan,
delete-orphan.
• If we put cascade = All , it responsible to work all the
operations.
Hibernate Flow
• Configuration

Configuration cf = new Configuration();


cf.configure(“hibernate.cfg.xml”);
• SessionFactory

SessionFactory sf = cf.buildSessionFactory();

• Session

Session session = sf.openSession();


• Transaction
Transaction tx = session.beginTransaction();

• Saving Object into database


session.save(s) – inserting object ‘s’ into DB

• Transaction commit, Connection close


tx.commit();
Sf.close();
How does Hibernate work?
Persistence layer framework?
Security components
How do you call aggregate functions in
hibernate HQL provides the aggregate
functions in hibernate.
• Yes, Hql supports aggregate functions.
• We can call aggregate functions using like this,
select avg(cat.weight), sum(cat.weight),
max(cat.weight), count(cat) from Cat cat
It supports :-
• avg(...), sum(...), min(...), max(...)
• count(*)
• count(...), count(distinct ...), count(all...)
How many ways configure
hibernate.cofig.xml file?
• Programmatic Configuration
Create configuration object
Configuration config=new Configuration();
Config.setProperty
addResource-add hbm
addClass-add class when use annotation
Pack all hbm files into jar and addJar(file)
• Use xml file(hibernate.cfg.xml)
• By creating property files with all config
param(hibernate.properties)
How to use positional parameters in
HQL? What are advantages?
• HQL use “?“ to represent positional parameter
values. You have to set your parameter according t
the position sequence.
Ex:- Query query = session.createQuery("from Employee where id =? or lastName=?" );
query.setString(0, empId);
query.setString(1, lastName);

Advantages:-
• We can pass dynamic data as part of query
execution. So it is make safe with SQL Injection
What are the advantage of joins in
hibernate?
• In hibernate joins are easily construct with using criteria api.
No need to remember complex sql join syntaxes.
• Joins are made using entity classes objects using ‘.’ operator.
• Easy to Read and Understand.
Ex:-
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
What is the usage of Criteria API?
• Criteria is suitable for executing Dynamic
Queries
• With Criteria we are safe with SQL Injection
• It is independent of Database language
syntaxes. It is purely java based object and
classes mechanism
• Pagination is supported by Criteria.
What are the differences between HQL
and native sql? When we go for Native
sql?
• HQL vs SQL
Represent sql query in the form of object
Get result as object, even it gets the child objects
DB type independent
Pagination
Include all oops concepts
What is the use of pagination?
• Structure and hierarchy reduce complexity
and improve readability.
• Pagination provides users with additional
navigation options for browsing through single
parts of the given article. Parts of the article
are usually referred to by numbers, hints,
arrows as well as “previous” and “next”-
buttons.
Any Experience on Top Link,
• It is an advanced object persistence and
object transformation framework .
• It provides development tool.
• Used with enterprise application to reduce
development time and maintenance work.
How to implement one to many
mapping in top link?
What is the difference between
openSession and getCurrentSession?
• openSession –creates new session .
• getCurrentSession-return current session
How to get Hibernate Session
instance?
• SessionFactory sessionFactory=new
Configuration().configure("hibernate.cfg.xml"
).buildSessionFactory();

• Session
session=sessionFactory.openSession();
Types of relationship
• One to One
• One to Many
• Many to One
• Many to Many
One to One
• Student and Address
Implementation
Public class Address
{
@OneToOne(targetEntity=Student.class,cascade
=CascadeType.ALL)
@JoinColumn(name="student_id")
private Student parent;
One to Many
• Customers and vendor tables
• Implementation
Public class vendor
@OneToMany(fetch=FetchType.LAZY,
targetEntity=Customers.class,
cascade=CascadeType.ALL)
@JoinColumn(name = "vendorid“)
private Set<Customer> customers;
Many to One
• Customers and Vendors
Public class Customers
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="venid",referencedColumn
Name="vid")
private Vendor parent;
Many to Many
• Ex:Categories and Items tables
Implementation
public class Categories
{
@ManyToMany(targetEntity=Item.class,cascade=Ca
scadeType.ALL)
@JoinTable(name="categories_items",joinColumns
=@JoinColumn(name="cat_id_fk"),inverseJoinCol
umns=@JoinColumn(name="item_id_fk"))
private Set items;
Public class item
{
@ManyToMany(targetEntity=Categories.class,m
appedBy="items")
private Set categories;
One-to-many mapping
• Using Foreign Key

• Using Join Table


One-to-many mapping example
One to One
• Using foreign key association - foreign key
column is created in owner entity
• Using a common join table - a new table will
be created with two columns, primary key of
two entities
• Using shared primary key -hibernate will
ensure that it will use a common primary key
value in both the tables.
Second level cache
• SessionFactory holds second level cache.
• Cache is available for all session objects created in the application,
not enabled by default
• Different vendors
EH Cache(r-o, nonstrict-r-w,r-w)
OS Cache(r-o, nonstrict-r-w,r-w)
Swarm Cache(r-o,nonstrict-r-w))
Jboss Cache(only transactional)
• Four stratergies
read-only
read-write
nonstrict-read-write(either one at a time)
transactional
Second level cache
Set properties in hibernate.cfg.xml
• <property name="cache.provider_class">org.hib
ernate.cache.EhCacheProvider</property>
• <property name="hibernate.cache.use_second_l
evel_cache">true</property>

Set cache usage –can be set on either class or


collection
@Cache(usage=CacheConcurrencyStrategy.READ_O
NLY)
Add ehcache.xml

<?xml version="1.0"?>
<ehcache>
<defaultCache
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="200" />

<cache name="Employee"
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="200" />
</ehcache>
Changes to be made for migrating
from one db to another db
• Change Dialect name in hibernate
configuration file.
What is the different between HQL vs
Criteria API
• 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
• 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.
Need to fetch only 10 entries from the
table , how to achieve it in hibernate
• By using
“setFirstResult()” and ”setMaxResults()”
methods we can achieve.
Ex:-
Query query = session.createQuery(HQL_QUERY);
query.setFirstResult(0);
query.setMaxResults(10);
List result = query.list();
Pagination in HB
• Using “setFirstResult()” and ”setMaxResults()”
methods we can achieve pagination in
Hibernate.
• In HQL pagination performance is less.
• In Criteria pagination we can improve the
performance.
what are the different types of caches
available
• Three types of caches are available in
Hibernate.
– First Level Cache
– Second Level Cache
– Query Level Cache
second level cache how will u
configure?
First enable second level cache in hibernate.cfg.xml file then using third
Partee vendor ehcache configuration we can achieve second level cache.

In hibernate.cfg.xml file:-
• <property name= "hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.EhCacheRegionFactory </property>
• <property
name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
• <property name="net.sf.ehcache.configurationResourceName">/
myehcache.xml </property>
In myehcache.xml file :-
<ehcache>
<cache name="com.somecompany.someproject.domain.Country"
maxEntriesLocalHeap="50“
eternal="false" timeToLiveSeconds="600"
<persistence strategy="localTempSwap"/>
/>
<cache name=
"com.somecompany.someproject.domain.Country.advancedSearchFacilities"
maxEntriesLocalHeap="450"
eternal="false" timeToLiveSeconds="600"
<persistence strategy="localTempSwap"/>
/>
</ehcache>
How will u avoid the duplicate records
fetching
• Using Set collection mapping
Which one u prefer the HQL and SQL
• HQL
I want to disable the First level cache
how I will do this ?
• No, Its not possible.
How Second level cache will be
refreshed
• Using evict() method we can clear the data
from cache.
sf.evictCollection(acp.getCache().getRegio
nName());
How to put condition with Criteria?
• Using Restrictions class
Ex:-
Criteria crit =
session.createCriteria(Product.class);
• Criterion price = Restrictions.gt("price",new
Double(25.0));
How to retrieve parent class and child
class data in hibernate
• Using fetchtype is EAGER.
@OneToMany(mappedBy = "parent",
cascade=CascadeType.ALL,
orphanRemoval=true, fetch = FetchType.EAGER)
We have 6 lakh data and need to insert
that data in DB? Which is the best way
to do this?
• Using batch processing or bulk Update
What is the method to do batch
process?
• Add hibernate.jdbc.batch_size property − in
hibernate.cfg.xml
• Iterate over for loop and using session.clear()
and session.flush() we can manage batch
processing.
Ex:- hibernate.cfg.xml file:-
<property name = "hibernate.jdbc.batch_size">
50
</property>
Cont.,
for ( int i=0; i<600000; i++ ) {
String fname = "First Name " + i;
String lname = "Last Name " + i;
Integer salary = i;
Employee employee = new Employee(fname, lname, salary);
session.save(employee);
if( i % 50 == 0 ) {
session.flush();
session.clear();
}}

Das könnte Ihnen auch gefallen