Wednesday, March 20, 2019

Hibernate interview questions

This blog is just for revision .
  • What is ORM ?
Object Relational Mapping : Object to database tables .
  • Explain Core Classes in hibernate .
  1. Configuration : load xml file .
  2. SessionFactory : thread safe
  3. Session : get connection with database , not thread safe , used to perform CRUD operations .
  4. Transaction :  commit and rollback operations . unit of work.
  5. Query : common query language for any type of database.
  6. Criteria : add restrictions and projections
  • Explain Hibernate configuration file 
contains database details used to initialize session factory .

  • Explain Hibernate Mapping file 
contains table and column details also contains the entity bean mapping .

  • Explain state of the entity in the persistence context .
Session is the persistence context which is used to manage relationship of the entities .
  1. transient : newly created object 
  2. persistent : associated with session ( session.save)
  3. detached : session closed 
  • How to use hibernate in spring ?
In application context.xml file specify

  1. the datasource bean  DriverManagerDataSource  
    • specify the username /password or jndi
  2. sessionfactory bean LocalSessionFactoryBean
  3. transaction bean HibernateTransactionManager
  4. tx:annotation driven 
  • What is hibernate dialect.
Different dialect for different databases
MySqlDialect , Oracle Dialect ,Db2 Dialect.


  • What are the different consistency anomalies in hibernate .
  1. dirty read .reading uncommitted data
  2. non repeatable read : second read returns different values for a row
  3. phantom read : second read returns different number of rows 

  • Explain isolation level .
  1. Read uncommitted
  2. Read committed :  
      4. Repeatable Read : second read will return same value 
      8. synchronized : does not allow concurrency

Isolation level is set using property hibernate.connection.isolation 


  • Explain the locking strategy based on isolation level .
  1. Read uncommitted : no lock 
  2. Read committed : lock on committed data
      4. Repeatable Read : lock on a block of  SQL
      8. Synchronized : full lock on table .

  • In which scenario repeatable read will return different data .
If the read is based on a condition and another thread inserts a row in database . Now for the second read we may get the new also if it satisfies the condition .
  • What is Caching in hibernate ?
  1. First level Catch : session cache of hibernate , enabled by default 
  2. Second Level Cache : optional , eg : Ehcache 
  3. Query Level Cache : cached query results . set hibernate.cache.use_query_cache property to true
  • What are the concurrency strategies for second level cache?
  1. Transactional : synchronized with the database .
  2. Read-write : if the transaction is not committed , the entity is fetched from database and referred from the cache .
  3. non strict read write : cache updated after data committed
  4. read only : used when data never gets changed .

  • What is dirty checking?

When hibernate loads an entity it keeps a copy of it in the memory, on tx.commit it compares the entity and the copy . If there are any changes, update statement is executed in the database.
  • Explain session.get
  1. Hits the database immediately.
  2. If record is not available in the database it returns null.
  • Explain session.load
  1. Returns proxy object without hitting the database.
  2. If the record is not available and when we try to access it through the proxy object we get Object Not Found Exception.
  • What is the difference between get and load ?
in case of no records in the database get returns null and load throws an exception .
  • What is the difference between save and persist ?
save return the id and persists returns nothing .persist marks the entity as persistent , does not generate Insert statement outside transaction boundaries . session.save on detached object will create a new row , session.persist on detached object will throw persistentobjectexception.

What is the difference between session.save and session.saveorupdate
save will insert the record if the Id is not available and throw exception if the Id is available. Saveorupdate will insert the record if the Id is not available, else it will update it.


  • What is the difference between update and merge ?
Update is used to update the persistent entity and Merge is used to update a detached entity .
  • What is the difference between session.flush and transaction.commit ?
flush synchronizes the persistent store with the state held  in memory .
commit commits the record to the database .
  • Explain Criteria
Used to filter record
cr =Session.createCriteria
cr.list();

  • Explain Restrictions
Used to add condition s to the query to compare the columns
Cr.add( Restrictions.eq("id" , 10));
  • Explain Projections
Used to call an aggregate method . Min , max , count .
Cr.setProjection( Projections.max("id"));

  • What is Declarative transaction management  ?
 transaction handling is not a part of business logic . 
using @Transactional :
  • What is Programmatic transaction management ?
transaction management is a part of business logic . 

  • Explain Different transaction manager used in spring .
  1. DataSourceTransactionManager : uses datasource 
  2. HibernateTransactionManager : uses sessionfactory
  3. JpaTransactionManager : uses entitiymanagerfactory 
  • Explain transaction propagation ?
using @Transactional( propagation=Propagation.
  1. REQUIRED : (default) if transaction is available use it otherwise create a new one. 
  2. REQUIRES_NEW : create a new transaction , commit / rollback is independent .
  3. NESTED : uses outer transaction but creates a savepoint to allow partial rollback and commit .

  • What is readOnly in @Transactional ?
used for only read operations
  • What are Value Types .
  1. Basic 
  2. Composite / Embedded
  3. Collection : for one to many .
  • Explain Many to Many .
Tables : Person , Project, PersonProject 
Entities :
Person : on projects set attribute add
  1. @ManyToMany 
  2. @JoinTable ( name=PersonProject , joinColums=@JoinColum , inverseJoinColumns=@JoinColum  )
Project: on persons set attribute add

  1.  @ManyToMany(mappedBy = "projects")


  • Explain One to Many
Tables : Person , Address

Entities :

  •   Explain Cascade type :
In case of mapping like one to one,or one to many , cascade type defines how changes in the entity will cascade to the mapped entity .
@ oneToMany cascade = Cascade Type.ALL
  1. All
  2. Persist
  3. Merge
  4. Refresh
  5. Remove
  6. Detach

  • How to lazy load the mapped classes

@oneToMany fetch = Fetch type.Lazy


  • What are the fetching strategies ?
  1. Join Fetching 
  2. Select Fetching 
  3. Sub select Fetching 
  4. Batch Fetching 

  • How to handle multiple databases ?
  1. @Table (schema= "")
  2. create two sessionfactory , use @Qualifier
  • How to handle distributed databases ?
use XA datasource , if  transaction is failed in one database , the entire transaction is roll backed .


  • What is the difference between jdbc and JTA?

2 phase commit can be handled using JTA only .

  •  Explain different ways of creating  EntityManager ?
  1. Container Managed : 
@PersistenceContext
EntityManager entityManager; 

2. Application Managed 
EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.model.student");
  • Explain  Anomalies in DBMS

1. Update : multiple rows needs to be updated to update a data .

2. Insert : cannot insert a row without supplementary data.

3. Delete : unable to delete a data as this will cause the important information to be deleted.



  • Explain normalization.

Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.
Terminology :
1. attribute : column
2. candidate key : primary key ( simple or composite )
3. prime attribute : column which is part of primary key
4. non prime attribute : column not part of primary key .
5. super key : any set of attributes which identifies a unique record .
6. functional dependency : B depends on A 
7. transitive dependency : B is dependent of A . C is dependent of B . So C has a transitive dependency on A .

1NF : attribute should be atomic.
2NF : non prime attribute should not depend on a subset of primary key
3NF : non prime attribute should not have transitive dependency with the super key .
BCNF : any functional dependency should be a super key .

No comments:

Post a Comment

ec2-user@ec2 Permission denied