You are on page 1of 13

Q Hibernate latest stable version is 5.

Q When not to used Hibernate framework ?


-When there is hierarical relationship between tables then hibernate is not good
because it will slow down the application.

Q What is Java persistance API ?


-JPA provides the specification for managing the relational data in application.
-JPA specifications is defined with annotation in javax.persistance package.
-Using JPA annotation we can write implementation independent code.

Q What is hibernate framework ?


-Hibernate is a ORM tool which provide programming technique to map java object to
relation a database table and vice versa
-Hibernate provide the implementation for JPA that make it a greate choice as a ORM
tool with the loose coupling benefits.
-Hibernate framework provide option to map java object to relation database table
with the use of JPA annotaion as well as XML based configuration.

Q What are the Benfits of using Hibernate ?


-Eliminates all boiler-plate code for JDBC and take care of managing resources,so
we can focus on business logic.
-Supports XML as well as JPA annotation, that makes our code implementation
independent.
-Supports HQL which is similar to SQL. HQL is fully object-oriented and understands
concept like inheritance,polymorphism.
-Hibernate supports Lazy initialization using proxy objects and perform actual
database query when required.
-Produces better performance using Hibernate caching.
-Allow executing native query.
-Hibernate implecitly provide transaction management.
-Hibernate provide option through which we can create table in database.
-Hibernate configuration provide JDBC connection as well as JNDI DataSource for
connection pool.

Q Name Some imp0rtant feature of interfaces in Hibernate framework?


-Session
-SessionFactory.
-Trasaction

What is hibernate configuration file ?(hibernate.cfg.xml)


-By default, it is placed under src/main/resource folder.
-configuration file contains database related configuration and used to initialize
SessionFactory.
-We provide database url,credential,JNDI resorce information in configuration
file.
-Also provide Dilect information so that hibernate know the database type.
-Also contains the Mapping file or class details.

<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
��������<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/java2novice</property>
��������<property name="hibernate.connection.username">root</property>
��������<property name="hibernate.connection.password">root</property>
��������<property
name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
��������<property name="show_sql">false</property>
����</session-factory>
</hibernate-configuration>

Q What is hibernate mapping file ?


-HibernateMapping file used to define the Entity bean property and database table
column mapping.
-We can used JPA anotation as well as XML configuration to map Entity field with
column in database.

Q Name annotation used for hibernate mapping?


-Some JPA and Hibernate annotation :
javax.persistance.Entity : used with class to specify that they are entity
beans.
javax.persistance.Table : used with Entity/class to define the table name.
javax.persistance.Access : used to define accesss type either field(default
value) or property(on getter/setter method)
javax.persistance.Id : used to define primary key.
javax.persistance.EmbeddedId : used to define composite primary key.
javax.persistance.Column : used o define coulmn name in table.
javax.persistance.GeneratedValue: used o define primary key generation type value.
javax.persistance.OneToOne :used to define one to one mappng between two Entity
javax.persistance.OneToMany :used to define one to Many mappng between two Entity
javax.persistance.ManyToMany
javax.persistance.ManyToOne
javax.persistance.CaseCade : used to define casecade between two entity beans.

Q What is hibernate SessionFactory and how to configure it ?


-SessionFactory is a factory class used to create session objects.
-SessionFactory is responsible to read the hibernate configuration parameter and
connect to database and provide session object.
-Single SessionFactory instance is created for an application and thread working
for client request get the session object from this factory class.
-Internal state of session factory is immutable ,once created cannot be change.
-SessionFactory also provide methods to get the class metadata,second level caching
information.
-Internal state is immutable hence it is thread-safe.

What is hibernate session ?


-Session is an interface between hibernate and java application.
-When transaction start session is created and transaction is end session expire.
-Session provide method to perform database operation like
create/read/update/delete.
-Session object is not thread safe ,every thread should get its own session
object and close it after its work is finished.

What is difference between openSession and getCurrentSession?


-openSession() : method always return new session
-getCurrentSession() : method return session bound to the context
Example:
//Current Session - no need to close
Session currentSession = sessionFactory.getCurrentSession();

//open new session


Session newSession = sessionFactory.openSession();
//perform db operations

//close session
newSession.close();

//open stateless session


StatelessSession statelessSession =
sessionFactory.openStatelessSession();

Difference between Hibernate Session get() and load() methods?


-Hibernate session provide diff method to load data from database : get() and
load().
-get() :
-It always hit the database and return the real object, an object that represent
the database row.
-If no row found return null.
-load data when call.
-support eager loading
-used when you want to check data availability.

-load():
-It will always return a �proxy� without hitting the database.
-return proxy object first and load data only when it required
-load is better because it support lazy loading.
-If no row found , it will throws an ObjectNotFoundException.
-throw exception when data is not found.we should used when data is exist.

What is hibernate caching?Explain Hibernate First Level cache?


-Hibernate caches query data to make application faster.
-Hibernate First level caching is associated with session object.
-Hibernate First level caching is enable by default and there is NO way to disable
it.
-However hibernate provides method through which we can delete selected objects
from the cache i.e evict() method or clear the cache completly using clear()
method.
-Any object cache in session will not be visible to other session.
-When sesssion close ,all objects will also be lost.
Example :-
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.

How to configure Hibernae Second Level cache using EHCache ?


-Second level cache is created in session factory scope and available with all the
session associated with session factory.
-When hibernate session try to load entity then look for the first level cache and
return value as a result of load method.
-If entity is not available in first level cache then check to the second level
cache and return value if available.
-If entity is not available in first level but avilable in second level then return
value from second level but also stored it in first level before returning as
response of load()method.
-If entity is not available in first level and second level then make database call
and store value in both cache level before returning as response of load()method.
-If some user or process make changes directly in database, then there is no way
that second level cache update itself until �timeToLiveSeconds� duration has passed
for that cache region.

Ehcache is a popular open source Java cache that can be used as a Hibernate second
level cache.
-EHCache is best choice to used second level cache.
1) Add hibernate-EHCache dependency in pom .xml or used jar file.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.5.Final</version>
</dependency>

2) Add below properties in hibernate configuration file.


<property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegi
onFactory</property>

<!-- For singleton factory -->


<!-- <property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEh
CacheRegionFactory</property>
-->

<!-- enable second level cache and query cache -->


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

3) Create EHCache configuration file.


<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">

<diskStore path="java.io.tmpdir/ehcache" />

<defaultCache maxEntriesLocalHeap="10000" eternal="false"


timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>

<cache name="employee" maxEntriesLocalHeap="10000" eternal="false"


timeToIdleSeconds="5" timeToLiveSeconds="10">
<persistence strategy="localTempSwap" />
</cache>

<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>

<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000" eternal="true">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
4) Annotate entity beans with @Cache annotation and caching strategy to use. For
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name = "ADDRESS")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Address {

5) Different caching-strategy :
-none : No caching will perform.
-read-only : if u performing read,but not modify instance of persistance class
then used read-only cache.
-read-write : If the application needs to update data, a read-write cache might be
appropriate.

What are different state of Entity Bean ?


Transient :
-When an object is never persisted or associated with any session ,its in transient
state.
-Transient object may be made persistance by calling save(),persist() or
saveOrUpdate().
-Persistance object may made transient by calling delete().

Persistent :
-When object is associated with a unique session it is in persistance state.
-Any instace return by a get() and load() method is persistent.

Detached :
-When an object is persistent but not associated with any session,its in detached
state.
-Detached object can be made persistent by calling update(), saveOrUpdate(),lock()
or replicate()

Difference betweem save(),persist() and saveOrUpdate method?


save() :
-Used to save entity to database.
-Invoked without transaction and if we have mapping object, then save only the
primary objects unless we flush the session.
-Also return save entity id immediately.

persist():
-persist is similar to save ,with transaction and add entity to persistance state.
-better to used because we need to perform database operation in transacion only.
-also persist doesn't return save entity id immediately.
-if we have mapping objects then save both objects at same time.

saveOrUpdate();
-results into save or update query based on input provided.
-If data persist in database update query is called.
-We can use saveOrUpdate() without transaction also but again we will face mapped
object not getting save untill we will flushed session.

merge():
-hibernate merge can be used to update existing values.
-method create copy of entity object we passed and return it.
-the return object is part of persistance context and tracked for any changes,
passed object is not tracked.

Q What happen if we don't used no-args constructor in Entity bean?


-If you don't have no-args constructor in entity beans hibernate will fail to
instantiate it and you will get HibernateException
-because hibernate uses Reflection API to create instance of entity bean ,Then
method Class.newInstance() is used for this and it required no-args constructor.

Q In Hibernate What is sorted collection and ordered collection,which is better?


Sorted collection :
-When we used sorting algorithm over collection to sort the data is called sorted
collection.
-For larger collection it may cause slow performance or OutOfMemory errors.
-Also the entity bean may have to implenents comprable and comparator interface for
it to work.

Ordered collection :
-If we are using hibernate framework to load collection data from database ,we can
used it's Criteria API to use "order by" clause.
-Order list is better then sorted list because the actual sorting is done at
database level which is faster and never cause memmory issues.

Q What are the collection types used in Hibernate?


collection types used in Hibernate for one-to-many relationship mappings.
-Bag
-Set
-List
-Array
-Map

Q How to implements JOIN in hibernate ?


-Using association : one-to-one / one-to-many etc.
-Using JOIN in the HQL query
-We can fire native query and use join keyword.

Q Why we should not make entity class final?


-Hibernate use proxy class for lazy loading of data ,this is done by extending the
entity bean .
-If entity bean is final then lazy load will not be possible.

Q What is HQL and what are it's benefits?


-Hibernate come with powerful object-oriented query language i.e HQL.
-Similar to SQL, but we used object instead of table name.
-HQL is case-insensitive excepts for java class and variable name.

Q What is Query catch in hibernate ?


-Hibernate implements a cache region for queries resultset.
-This is optional feature and required additional steps to used.

-add below property in hibenate configuration file.


<property name="hibernate.cache.use_query_cache">true</property>

-and in code we need to add setCacheable(true)


Query query = session.createQuery("from Employee");
query.setCacheable(true);
query.setCacheRegion("ALL_EMP");

Q Can we excute native SQL query ?


Yes we can, but its not recommended because we loose benefits reated to hibernate
association and hibernate first level caching.

Q What is the benefits of Hibernate Criteria API ?


-Hibernate provide criteria API that is more object oriented for querying database.
-It only used to fetch the results from the database.
-Insert/update/delete is not allow in criteria.

-CriteriaAPI provide Projection that we can used for aggregate functions such as
sum(),min(),max() etc.
-CriteriaAPI can be used for fetching results with conditions,usefull methods is
add() where we can add Restriction.
-CriteriaAPI can be used with Projection List to fetch selected column only.
-CriteriaAPI can be used for join queries by joining multiple tables.
-CriteriaAPI provides addOrder() methods that we can use for ordering results.

import java.util.Arrays;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateCriteriaExamples {

@SuppressWarnings("unchecked")
public static void main(String[] args) {
// Prep work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();

//Get All Employees


Criteria criteria = session.createCriteria(Employee.class);
List<Employee> empList = criteria.list();
for(Employee emp : empList){
System.out.println("ID="+emp.getId()+",
Zipcode="+emp.getAddress().getZipcode());
}

// Get with ID, creating new Criteria to remove all the settings
criteria = session.createCriteria(Employee.class)
.add(Restrictions.eq("id", new Long(3)));
Employee emp = (Employee) criteria.uniqueResult();
System.out.println("Name=" + emp.getName() + ", City="
+ emp.getAddress().getCity());

//Pagination Example
empList = session.createCriteria(Employee.class)
.addOrder(Order.desc("id"))
.setFirstResult(0)
.setMaxResults(2)
.list();
for(Employee emp4 : empList){
System.out.println("Paginated Employees::"+emp4.getId()
+","+emp4.getAddress().getCity());
}

//Like example
empList = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "%i%"))
.list();
for(Employee emp4 : empList){
System.out.println("Employees having 'i' in
name::"+emp4.getName()+","+emp4.getAddress().getCity());
}

//Projections example
long count = (Long) session.createCriteria(Employee.class)
.setProjection(Projections.rowCount())
.add(Restrictions.like("name", "%i%"))
.uniqueResult();
System.out.println("Number of employees with 'i' in name="+count);

//using Projections for sum, min, max aggregation functions


double sumSalary = (Double) session.createCriteria(Employee.class)
.setProjection(Projections.sum("salary"))
.uniqueResult();
System.out.println("Sum of Salaries="+sumSalary);

//Join example for selecting few columns


criteria = session.createCriteria(Employee.class, "employee");
criteria.setFetchMode("employee.address", FetchMode.JOIN);
criteria.createAlias("employee.address", "address"); // inner join by
default

ProjectionList columns = Projections.projectionList()


.add(Projections.property("name"))
.add(Projections.property("address.city"));
criteria.setProjection(columns);

List<Object[]> list = criteria.list();


for(Object[] arr : list){
System.out.println(Arrays.toString(arr));
}

// Rollback transaction to avoid messing test data


tx.commit();
// closing hibernate resources
sessionFactory.close();
}
}

Q What is your choice while writing queries within Hibernate - criteria or HQL ?
- I prefer using Criteria for Dynamic queries and HQL for static queries.

Q How Hibernate generated SQL queries in log files ?


-add below property .
<property name="hibernate.show_sql">true</property>
-We can use it in developement or testing environment and turn it off in production
environment.

Q What is hibernate Proxy and how it helps in Lazy Loading?


-Hibernate used proxy object to supports lazy loading.
-basically when u load data from databse , hibernate doesn't load all the mapped
objects.
-If the linked entity not in the session cache then proxy code will go to the
database and load linked object.

Q How transaction management work in Hibernate ?


-SessionFactory gives session object ,which contains beginTransaction().
-call to this beginTransaction() which return transaction reference which we can
used letter on either to commit or rollback the transaction.
-Hibernate transaction automaticaly roll-back transaction when needed.

Q What is casecading and what are different types of casecading?


-When we have relationship between entities, then we need to define how different
operation will affects other entity.
-This is done by casecading.
CascadeType.PERSIST: It means that the save() and persist() operations in the
hibernate cascade to the related entities.
CascadeType.MERGE: It means that the related entities are joined when the
owning entity is joined.
CascadeType.REMOVE: It means that the related entities are deleted when the
owning entity is deleted.
CascadeType.DETACH: It detaches all the related entities if a manual detach
occurs.
CascadeType.REFRESH: It works similar to the refresh() operation in the
hibernate.
CascadeType.ALL: It is an alternative for performing all the above cascade
operations in the hibernate framework.

NOTE :- https://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-
cascadetype-persist-example/#:~:text=Cascading%20is%20a%20phenomenon
%20involving,CascadeType.

Q How to intergrate log4J logging in hinernate application?


-Add log4J dependency in maven or add jar file.
-Create lg4j.xml configuration file and keep it in class path.(file name can be
user define)
-Create Logger instance in java classes and start logging.

Q Which design patter used in Hibernate Framework ?


-Proxy pattern for lazy load.
-Factory pattern in SessionFactory.

Q Best practice to used Hibernate Framework ?


-Always check primary key field access.If it is generated at database layer then
you should not have a setter for this.
-If access type is property then annotation should be used with getter method.
-Used native query only when it can't be done using HQL.
-If you have to sort collection then use order list instead of collection API.
-Avoid many-to-many relationship,it can be easily implemented by one-to-many and
many-to-one.
-For collection try to used List, Set, Maps avoid array because you dont get
benefits of lazy loading.
-Prefer lazy fetch for association.
-Always rollback transaction and close connection.

Q HibernateValidation ?
-Data validation must be done before it persist.
-Validation is cross cutting concern so we should try to keep it apart from
business logic.
-Need to add dependency : hibernate-validator and hibernate-validation.
-Annotaion use for validation :
@NotNull
@unique
@Email
@Min
@Max
@Size
@CreditCardNumber
@Valid

Explain Criteria API ?


Example :
List
employees=session.createCriteria(Employee.class).add(Restriction.like("name","p
%")).addOrder(Order.asc("name")).list();

Q Can we connect Multiple database using hibernate ?


-YES, Hibernate is design to be used with large set of databases.
-The details of those databases are configure in " hibernate.cfg.xml ".
-For example YOU want to connect to Oracle and Derby
-Create 2 config file one for oracle and second for Derby.
-Create Two Session Factory Object for TWO config file.

Q How does hibernate code look like ?


Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");
session.save(mpc);
tx.commit();
session.close();

Q Should all the mapping files of hibernate have .hbm.xml extension to work
properly?
No not mandatory to keep .hbm.xml only.

Q What are the two types of collections in hibernate?


a. Sorted Collection
b. Order Collection

Q What�s the difference between session.save() and session.saveOrUpdate() methods


in hibernate?
session.save()
-Insert if its unique key means new record.
-fail if record already exist.

session.saveOrUpdate()
-Insert if its unique key means new record.
-update if record already exist.
Q What are the benefits of hibernate over JDBC?
hibernate :
-database independent.
-no need to write connection pool code, manage by hibernate internally

JDBC:
-database specific query.
-need to write connection code.

Q How can we get hibernate statistics?


-SessionFactory.getStatistics()

Q How can we reduce database write action times in Hibernate?


-Hibernate provides dirty checking feature which can be used to reduce database
write times.
-Dirty checking feature of hibernate updates only those fields which require a
change while keeps others unchanged.

Q What�s the usage of callback interfaces in hibernate?


-Callback interfaces of hibernate are useful in receiving event notifications from
objects.
- For example, when an object is loaded or deleted, an event is generated and
notification is sent using callback interfaces.

Q How can we reattach any detached objects in Hibernate?


-Objects which have been detached and are no longer associated with any persistent
entities can be reattached by calling
session.merge() method of session class.

Q What are different ways to disable hibernate second level cache?


a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider

Q Does hibernate support polymorphism?


Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism
associations

Q What are the three inheritance models of hibernate?


a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class

Q How can we map the classes as immutable?


@Immutable
If we don�t want an application to update or delete objects of a class in
hibernate, we can make the class as immutable by setting mutable=false

Q What�s general hibernate flow using RDBMS?


General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.

Q Explain the different ways Hibernate manages concurrency?


� Automatic versioning
� Detached object
� Extended user sessions

Q What is meant by Hibernate tuning?


-Optimizing the performance of Hibernate applications is known as Hibernate tuning.

The performance tuning strategies for Hibernate are:


-SQL Optimization
-Session Management
-Data Caching

Q What are the different states of a persistent entity?


-Transient: This is not associated with the Session and has no representation in
the database.
-Persistent: You can make a transient instance persistent by associating it with a
Session.
-Detached: If you close the Hibernate Session, the persistent instance will become
a detached instance.

Q What are the best practices to follow with Hibernate framework?


-Always check the primary key field access, if it�s generated at the database layer
then you should not have a setter for this.
-If access type is property, make sure annotations are used with getter methods and
not setter methods.
-Avoid mixing of using annotations on both filed and getter methods.
-Use native sql query only when it can�t be done using HQL, such as using the
database-specific feature.
-If you have to sort the collection, use ordered list rather than sorting it using
Collection API.
-For web applications, always try to use JNDI DataSource rather than configuring to
create a connection in hibernate.
-Avoid Many-to-Many relationships, it can be easily implemented using bidirectional
One-to-Many and Many-to-One relationships.
-For collections, try to use Lists, maps and sets. Avoid array because you don�t
get benefit of lazy loading.
-Do not treat exceptions as recoverable, roll back the Transaction and close the
Session. If you do not do this, Hibernate cannot guarantee that the in-memory state
accurately represents the persistent state.
-Prefer DAO pattern for exposing the different methods that can be used with entity
bean
-Prefer lazy fetching for associations

Q How to declare date in hibernate


@Entity
public class Author
{
����@Temporal(TemporalType.DATE)
����private Date dateOfBirth;
����...
}

https://www.callicoder.com/hibernate-spring-boot-jpa-composite-primary-key-example/
https://www.journaldev.com/3633/hibernate-interview-questions-and-
answers#hibernate-overview

You might also like