Академический Документы
Профессиональный Документы
Культура Документы
-- To get each Employee, get Employee details-----------N number of select statements for Employee
@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"
)
}
)
SessionFactory sf = cf.buildSessionFactory();
• Session
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
<?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();
}}