Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Thursday, 10 October 2013

Hibernate Interview Questions Part - 2



Interview Questions

Questions: - What is the use of inverse in Hibernate?

Answer: - The “inverse” keyword is always declare in one-to-many and many-to-many relationship. We 
don’t have “inverse” keyword in many-to-one relationship. “inverse” is used to decide which side is the relationship owner will manage the relationship (insert or update of the foreign key column). It means which side is responsible to take care of the relationship.

inverse = “true” describes that this is the relationship owner, where as inverse=”false” (default) means it’s not the relationship owner.

Questions: - What is the use of cascade in Hibernate?

Answer: -

Cascade values are
1.      none (default)
2.      save
3.      update
4.      save-update
5.      delete
6.      all
7.      all-delete-orphan

If cascade = “none” and if we execute save (or update or delete) operation on parent class object, then child class objects will not be effected.

If we write cascade = “all”, then the operations like save or delete or update executed at parent class object will be effected to child class object also.

If we write cascade = “save-update”, then the operations like save and update executed at parent class object will also be effected to child class object also.

In an application, if a child record is removed from the collection and if we want to remove that child record immediately from the database, then we need to set the cascade =”all-delete-orphan”


Questions: - What is the use of BAG collection in hibernate?

Answer: - If our table does not have an index column, and we want to use collection property type, then in this case we can use <bag> Collection property in Hibernate. When a collection of data is retrieved and assigned to bag collection then bag does not retain its order but it can be optionally sorted or ordered. A bag permit duplicates it means it does not have primary key. So finally we can tell that a bag is an unordered, unkeyed collection that can contain the same element multiple times.


Questions: - What is optimistic locking in Hibernate?
Answer: - When we load object in one transaction, modify the data and save it later in another transaction then in this situation Hibernate optimistic locking works. This locking ensures that some other transaction hasn’t changed that same object in the database in between. However, optimistic locking doesn't affect isolation of concurrent transactions.  


Questions: - What is transactional write behind in Hibernate?

Answer: - When we call session.save(Object) in the hibernate code then it does not fire the SQL insert query immediately. Similarly when we call session.delete(Object) or session.update(Object)  then it will not fire the corresponding SQL queries(delete and update queries) immediately.

The meaning is thatwhen objects associated with persistence context are modified, the changes are not immediately propagated to the database.

Hibernate collects all such database operations associated with a transaction and create minimum set of SQL queries and execute them. This will provide us 2 advantages:-

  • In case of multiple updates or inserts or deletes, Hibernate is able to make use of the JDBC Batch API to optimize performance.
  • Every property change in the object does not cause a separate sql update query to be executed.
  • Avoiding unwanted SQL queries ensures minimum hits to database thus reducing the network latency.

This delayed execution of sql queries is known as transactional write behind.

Saturday, 7 September 2013

Hibernate Interview Questions

Interview Questions



Question: - What is Session in Hibernate?

Answer: - Session is an interface in hibernate. We can get Session objects using SessionFactory references. Session is a wrapper for “java.sql.Connection”.It performs manipulation on DB entities. This is the basic interface for hibernate framework. Session object is light weight and can be created and destroyed without expensive process. It is short lived object and not thread safe. It works as a factory for org.hibernate.Transaction”.It maintains the first level cache by default and this can be used while searching for the objects using identifier.

Question: - What session.refresh() method will do?

Answer: - session.refresh():- During the bulk update to the DB with hibernate, the changes made are not replicated to the entities stored in the current session. So calling session.refresh will load the modifications to session entities.

Question: - What session.flush () method will do?

Answer: - session.flush ():- This tells Hibernate to execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in the session-level cache. session.flush ()call will save the object instances to the database.

Question: - What session.clear () method will do?

Answer: - session.clear():- session.clear() method call can be used to clear the persistance context. It completely clears the session. This method call evicts all the objects from the session.

Question: - What session.evict (Object obj) method will do?

Answer: - session.evict(Object object): This method call will remove the instance that is passed as an argument in the evict method from the session cache and make a persistent object as a detached object.

Question: - What session.save() method will do?

Answer: - session.save() :This method call does an insert and will fail if the primary key is already available.

Question: - What session.saveOrUpdate()method will do?

Answer: - session.saveOrUpdate() :This method call does a select first to determine if it needs to do an insert or an update. Insert data if primary key is not already available in database otherwise do update data.

Question: - What session.persist () method will do?

Answer: - session.persist() :This method call does the same like session.save().
But session.save() returns Serializable object but session.persist() returns void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn’t.

Question: - What session.delete()method will do?

Answer: - session.delete(Object obj):- This method call will remove a persistent instance from the datastore.

Question: - What are the Fetching Strategies in hibernate?
Answer: -Fetching Strategies

Below are the fetching strategies.

1. fetch-”join” = this disable the lazy loading, always load all the collections and entities.
2. fetch-”select” (default) = this will lazily load all the collections and entities.
3. fetch-”subselect” = this will group its collection into a sub select statement.

Note: - These stretegies we can use in FetchMode.

Question: - What is Lazy and Eager loading strategies?

Answer: - The EAGER strategy is a hint given to the persistence provider that at runtime the data must be eagerly fetched (fetch in one query).
The LAZY strategy is a hint given to the persistence provider that at runtime the data should be fetched lazily when it is first accessed (fetch when needed as sub-queries).
  •  EAGER Fetch — get results in one query ( parent and child both ) 
  • LAZY Fetch – get results as sub-query.
For Example:
Suppose we have an entity called Student and another entity called Department.
The Student entity might have some basic properties such as id, name etc. as well as a property called Department.
Now Using Eager Loading, when we load a Student from the database, Hibernate will load student id, name fields and it also loads related Department details using the getDepartment() method -This is called  eager loading.
When a Student is associated with many Departments then it is not efficient to load its entire Department because it will create overhead on performance as they are not needed. So in such cases, we can declare that we want Department to be loaded when they are actually needed. This is called lazy loading.


Question: - what is the difference between fetch = FetchType.LAZY and FetchMode.SELECT.

Answer: -
FetchType:- There are two FetchType categories:-
LAZY and EAGER
Fetch type  refers to when Hibernate will fetch the association, whether in advance when it fetches the entity (eager), or whether it waits for the code to ask for the association (lazy).
Fetch mode refers to howHibernate will fetch the association, i.e. does it use an extra SELECT statement, or does it use a join. For example:-
@Fetch(FetchMode.SELECT)

      @OneToOne(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

      privateCustomerAddress customerAddress;

About Hibernate SessionFactory!

Fact about hibernate SessionFactory


Questions: - What is SessionFactory in hibernate?


Answer: - In Hibernate, SessionFactory is an interface, which is available in “org.hibernate” package. The delivery of session objects to hibernate applications is done by this interface. The SessionFactory object should be instantiated once during the application initialization.
  •  Session factory is long lived and thread safe object, so it can be shared in multithreaded environment.
  •  Generally only one SessionFactory is enough for an application but if application is interacting with more than one database then one SessionFactory should be created for one database.

Configuration cfg=new Configuration();   // This statement will create an empty object.
cfg=cfg.configure();


when we called  configure()  method then It looks for hibernate.cfg.xml configuration file and it also looks for Hibernate mapping(.hbm) file.

 SessionFactory sessionfactory = cfg.buildSessionFactory();
  • SessionFactory object will be created once and will be used by multiple users. It’s a single data store point and it is thread safe. Many threads can access this concurrently.
  • Session Factory object is the factory for session objects and it must be built only once at startup.

  • SessionFactory acts as a client of  “org.hibernate.connection.ConnectionProvider”.

  • SessionFactory maintains a second level cache of data that is reusable between transactions at a process or cluster level.

If we are using two databases like mysql and oracle in our hibernate application then we need to build two SessionFactory objects like below:-
Configuration configuration =new Configuration ();
Configuration cfg1= configuration.configure(“hibernate-mysql.cfg.xml”);
SessionFactory sessionfactory1=cfg1.buildSessionFactory ();

Configuration cfg2= configuration.configure(“hibernate-oracle.cfg.xml”);
SessionFactory sessionfactory2=cfg2.buildSessionFactory ();

In an application, to get the SessionFactory objects we should create a utility class and using their methods we should get the SessionFactory object. Below is the example of HibernateUtility Class.

package com.gaurav.common.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtility {
                privatestatic final SessionFactory sessionFactory = createSessionFactory();

                privatestatic SessionFactory createSessionFactory() {
                                try{
                                                returnnew Configuration().configure().buildSessionFactory();
                                } catch (Exception ex) {
                                                System.err.println("SessionFactory creation failed");
                                                thrownew ExceptionInInitializerError(ex);
                                }
                }

                /**
                 * @return the sessionfactory
                 */
                publicstatic SessionFactory getSessionfactory() {
                                returnsessionFactory;
                }

}

So, if we are using the above utility then we can use below code to get the session objects.



SessionFactory sf = HibernateUtility.getSessionfactory();

                                Session session = sf.openSession();