1. What is Hibernate?
Hibernate is object-relational mapping (ORM) and persistence framework that allows you to map Java objects to relational database tables using (XML) configuration files. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. Along with mapping from Java classes to database tables (and from Java data types to SQL data types), it also provides data query and retrieval facilities.
2. What is object-relational mapping (ORM)?
Object Relational Mapping (ORM) is a programming technique used to convert data between relational databases and object oriented programming languages(Java).ORM uses metadata descriptor to connect object code to relational database where as Object code is written in OOP language such as JAVA.
Hibernate is object-relational mapping (ORM) and persistence framework that allows you to map Java objects to relational database tables using (XML) configuration files. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. Along with mapping from Java classes to database tables (and from Java data types to SQL data types), it also provides data query and retrieval facilities.
2. What is object-relational mapping (ORM)?
Object Relational Mapping (ORM) is a programming technique used to convert data between relational databases and object oriented programming languages(Java).ORM uses metadata descriptor to connect object code to relational database where as Object code is written in OOP language such as JAVA.
3. What are the advantages of Hibernate?
- Hibernate uses XML files for mapping Java classes to database tables and without writing any line of code.
- Hibernate improves the productivity through high-level object-oriented API, we need to write less java code and no more need of SQLs.
- Provides simple APIs for storing and retrieving(API for performing basic CRUD operations and API to express queries referring to classes) Java objects directly to and from the database.
- As hibernate uses XML files for mapping, If there is change in Database or in any table then the only need to change XML file properties.
- It minimizes the database access as it has smart fetching technics and provide simple querying of data.
- We can easily maintain the application using hibernate as it requires leess code to write.
- Hibernate improves the performance by providing Sophisticated caching, Lazy loading and Eager loading.
4. What are the Core interfaces in Hibernate?
Following are the core interfaces used to store and retrieve persistent objects and control transactions in hibernate framework.
- Session interface
- SessionFactory interface
- Configuration interface
- Transaction interface
- Query and Criteria interfaces
5. What is SessionFactory in Hibernate?
The application gets the Session instances from a SessionFactory(as name suggest it is a factory to create hibernate Session objects). SessionFactory is built up on start-up and used by application to get session objects. It is thread safe so multiple threads can use session factory. Generally application has only one SessionFactory. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work. at internal state of SessionFactory, it contains all metadata about object relational mapping and which is immutable so it can not be changed once created.
We can create the session factory as follows:
The application gets the Session instances from a SessionFactory(as name suggest it is a factory to create hibernate Session objects). SessionFactory is built up on start-up and used by application to get session objects. It is thread safe so multiple threads can use session factory. Generally application has only one SessionFactory. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work. at internal state of SessionFactory, it contains all metadata about object relational mapping and which is immutable so it can not be changed once created.
We can create the session factory as follows:
SessionFactory sessionFactory = configuration.buildSessionFactory();
6. What is session in Hibernate?
Session represents a
small unit of task in hibernate. Session is a single-threaded,
short-lived object representing a conversation between the application
and the persistent store(Session obtains lazy database connection). It is "not thread-safe" that means we can not share Hibernate Session between multiple threads. It allows us to create query objects to retrieve persistent objects. Though Session obtains database connection lazily, it
is good practice to close session as soon as we are done with it.
Session holds the first level cache of persistent objects which is used
when navigating the object graph or looking up objects by an identifier.
We can create the session object from session factory as follows:
Session session = sessionFactory.openSession();
7. How do we map java objects to database tables?
Hibernate uses xml files for mapping java objects with database tables. So for this we need to have java classes. So
Hibernate uses xml files for mapping java objects with database tables. So for this we need to have java classes. So
- First we need to create Java objects( we need to create beans with setters and getter methods.)
- Then we need to write xml files (hbm.xml), where we map java class to table and database columns to Java class variables.
8. What is the flow of hibernate how it communicate with RDBMS?
- First need to loads the Hibernate configuration file and need to create configuration object then it will automatically load all mapping(hbm.xml) files.
- Then need to create session factory object using configuration object.
- After that need to get session from the session factory and need to create HDL query.
- After that need to execute query to get result. Hibernate offers a query language(Hibernate query Language (HQL)) that provides a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. HQL is an object-oriented extension to SQL.
9. What is the differences between get() and load() methods in Hibernate?
I. Performance: get()
will hit the database if object is not found in the cache and returned
completely initialized object, which may involve several database call
while load() method can return proxy, if object is not found in cache and only hit database if any method other than getId() is called. This can save lot of performance in some cases.
II. Behavior: get() method of Hibernate Session class returns null if object is not found in cache as well as on database while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.
III. Proxy: get()
method never returns a proxy, it either returns null or fully
initialized Object, while load() method may return proxy, which is the
object with ID but without initializing other properties, which is
lazily initialized. If you are just using returned object for creating
relationship and only need Id then load() is the way to go.
10. What does named SQL query mean?
We can specify the sql
queries in mapping xml file using <sql-query> tag and we can call
where ever required. This is called named sql query. So named sql query
is a SQL query which is defined in mapping file
using <sql-query> tag and called
using Session.getNamedQuery() method. Named query allows us to refer a
particular query by the name you provided. By the way we can define
named query in hibernate either by using annotations or xml mapping
file(said above). @NameQuery is used to define single named query
and @NameQueries is used to define multiple named query in hibernate.
11. What are the differences between save(), persist() and saveOrUpdate() methods in hibernate?
All three methods(save(), saveOrUpdate() and persist() ) are used to save objects into database, but has subtle differences like save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.
And return type of save() is a Serializable object and where as return type of persist() method is void.
Differences between save() , persist() and saveOrUpdate():
Main difference between save() and saveOrUpdate() method is save() inserts record into database and generates a "new identifier" but saveOrUpdate can either insert or update based upon existence of record. So saveOrUpdate() method is more flexible in terms of use but it requires more processing to find out whether record already exists in table or not. Finally the summary is save() method saves records into database by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. But saveOrUpdate() method either insert or update based upon existence of object in database like if persistence object already exists in database then it will uses the UPDATE SQL and if there is no corresponding object in database than it will use INSERT.
Coming to persist(), it is Similar to save() method like persist also inserts records into database but return type of persist is void while return type of save is Serializable object.
persist() method guarantees that it will not execute an insert statement if it is called outside of transaction boundaries where as save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier then this insert happens immediately, no matter if we are inside or outside of a transaction.Because of this behavior(above behavior like boundaries), persist() method is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
12. What is the difference between sorted collection and ordered collection?
Sorted collection performs sorting on collection by using the sorting features provided by the Java collections framework. The sorting feature occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.
Simply A sorted collection is sorted in memory by using Java Comparator, And order collection is sorting a collection by specifying the order-by clause.
So for large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.
For small collection, sorted collection will be more efficient way to sort it.
13. What are the difference between transient, persistent and detached objects in Hibernate?
Object can remain have three state transient, persistent or detached in Hibernate.
Persistent : An object which is associated with Hibernate session is called persistent object. So any changes in this object will reflect in database based upon your flush strategy( i.e. automatic flush whenever any property of object change or explicit flushing by calling Session.flush() method).
Detached: If an object which is earlier associated with Session, but currently not associated with it are called detached object. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session.
Transient: Transient objects are newly created instance of persistence class, which is never associated with any Hibernate Session. Similarly you can call persist() or save() methods to make transient object persistent. Please remember, here transient does not represent transient keyword in Java, which is altogether different thing.
14. What is the use of session.lock() method in hibernate?
session.lock() method is used to reattach an object which has been detached earlier without synchronizing or updating with database. So it may lead to lack of synchronization in data and hence we need to be very careful while using lock() method of session.
15. What are the difference between session.update() and session.lock() methods?
Both session.update() and session.lock() methods are used for reattaching the a detached object. But session.lock() method simply reattach the object without checking(or)updating the database, where as update() method will check the database while reattaching the object. Here session.lock() will assumption that the database is sync with the detached object. So it will not check with database. So use session.lock() method only if we are absolutely sure that the database is sync with detached object or if it does not matter because we will be overwriting all the columns that would have changed later on within the same transaction.
16. Why we need to provide no argument constructor in Hibernate Entities?
Every Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API, by calling "Class.newInstance()" method. If we did not specify the no argument constructor, then "Class.newInstance()" will throw InstantiationException.
17. What are the different types of caches used by Hibernate?
Hibernate uses two different type of caches for objects and those are :
1. FirstLevelCache
2. SecondLevelCache
FirstLevelCache: It is associated with session object. Hibernate uses this cache to reduce the number of SQL queries it needs to generate within a given transaction. It is default cache used by hibernate on a per-transaction basis.
SecondLevelCache: It is associated with SessionFactory object and can improve performance by saving few database round trip. Hibernate always tries to retrieve objects from session. If this fails it tries to retrieve objects from secondlevel cache. If this also fails then it loads objects directly from database. Hibernate's static initialize() method(which populates a proxy object) will attempt to hit second level cache before going to database. Hibernate class provides static methods for manipulation of proxies.Second level Cache is available to whole application rather than any particular session.
18.What is query cache in Hibernate?
Query Cache is responsible to store/cache the results of query(to be more precise keys of objects returned by queries) for future calls.It can be used along with second level cache for improved performance. Hibernate uses/support various open source caching solution to implement Query Cache.
Ex: Query query = session.createQuery("from Employee as e where e.id=?");
query.setInt(0, "137");
query.setCacheable(true); // query is cacheable
List list = query.list();
11. What are the differences between save(), persist() and saveOrUpdate() methods in hibernate?
All three methods(save(), saveOrUpdate() and persist() ) are used to save objects into database, but has subtle differences like save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.
And return type of save() is a Serializable object and where as return type of persist() method is void.
Differences between save() , persist() and saveOrUpdate():
Main difference between save() and saveOrUpdate() method is save() inserts record into database and generates a "new identifier" but saveOrUpdate can either insert or update based upon existence of record. So saveOrUpdate() method is more flexible in terms of use but it requires more processing to find out whether record already exists in table or not. Finally the summary is save() method saves records into database by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. But saveOrUpdate() method either insert or update based upon existence of object in database like if persistence object already exists in database then it will uses the UPDATE SQL and if there is no corresponding object in database than it will use INSERT.
Coming to persist(), it is Similar to save() method like persist also inserts records into database but return type of persist is void while return type of save is Serializable object.
persist() method guarantees that it will not execute an insert statement if it is called outside of transaction boundaries where as save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier then this insert happens immediately, no matter if we are inside or outside of a transaction.Because of this behavior(above behavior like boundaries), persist() method is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
12. What is the difference between sorted collection and ordered collection?
Sorted collection performs sorting on collection by using the sorting features provided by the Java collections framework. The sorting feature occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.
Simply A sorted collection is sorted in memory by using Java Comparator, And order collection is sorting a collection by specifying the order-by clause.
So for large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.
For small collection, sorted collection will be more efficient way to sort it.
13. What are the difference between transient, persistent and detached objects in Hibernate?
Object can remain have three state transient, persistent or detached in Hibernate.
Persistent : An object which is associated with Hibernate session is called persistent object. So any changes in this object will reflect in database based upon your flush strategy( i.e. automatic flush whenever any property of object change or explicit flushing by calling Session.flush() method).
Detached: If an object which is earlier associated with Session, but currently not associated with it are called detached object. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session.
Transient: Transient objects are newly created instance of persistence class, which is never associated with any Hibernate Session. Similarly you can call persist() or save() methods to make transient object persistent. Please remember, here transient does not represent transient keyword in Java, which is altogether different thing.
14. What is the use of session.lock() method in hibernate?
session.lock() method is used to reattach an object which has been detached earlier without synchronizing or updating with database. So it may lead to lack of synchronization in data and hence we need to be very careful while using lock() method of session.
15. What are the difference between session.update() and session.lock() methods?
Both session.update() and session.lock() methods are used for reattaching the a detached object. But session.lock() method simply reattach the object without checking(or)updating the database, where as update() method will check the database while reattaching the object. Here session.lock() will assumption that the database is sync with the detached object. So it will not check with database. So use session.lock() method only if we are absolutely sure that the database is sync with detached object or if it does not matter because we will be overwriting all the columns that would have changed later on within the same transaction.
16. Why we need to provide no argument constructor in Hibernate Entities?
Every Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API, by calling "Class.newInstance()" method. If we did not specify the no argument constructor, then "Class.newInstance()" will throw InstantiationException.
17. What are the different types of caches used by Hibernate?
Hibernate uses two different type of caches for objects and those are :
1. FirstLevelCache
2. SecondLevelCache
FirstLevelCache: It is associated with session object. Hibernate uses this cache to reduce the number of SQL queries it needs to generate within a given transaction. It is default cache used by hibernate on a per-transaction basis.
SecondLevelCache: It is associated with SessionFactory object and can improve performance by saving few database round trip. Hibernate always tries to retrieve objects from session. If this fails it tries to retrieve objects from secondlevel cache. If this also fails then it loads objects directly from database. Hibernate's static initialize() method(which populates a proxy object) will attempt to hit second level cache before going to database. Hibernate class provides static methods for manipulation of proxies.Second level Cache is available to whole application rather than any particular session.
18.What is query cache in Hibernate?
Query Cache is responsible to store/cache the results of query(to be more precise keys of objects returned by queries) for future calls.It can be used along with second level cache for improved performance. Hibernate uses/support various open source caching solution to implement Query Cache.
Ex: Query query = session.createQuery("from Employee as e where e.id=?");
query.setInt(0, "137");
query.setCacheable(true); // query is cacheable
List list = query.list();
No comments:
Post a Comment