Tuesday, November 5, 2013

Hibernate Questions

1.  What is Hibernate?
--------------------------
Hibernate is an object-relational mapping tool, a persistence framework.

2. What is ORM
---------------
Object-relational mapping of database tables to domain object classes. ORM resolve Object-Relational Impedance Mismatch sometime called paradigm mismatch viz

Inheritance:  RDBMSs do not define anything regarding this,  some databases do have subtype support but it is completely non-standardized.

Identity : RDBMS defines exactly one notion of 'sameness' the primary key, but oop defines both object identity (a==b) and object equality (a.equals(b)).

Associations : Associations can be represented as unidirectional/bidirectional in OOP whereas RDBMSs use the notion of foreign keys.

Data navigation : navigate from one association to an other walking the object network.RDBMS use JOINs.

3. Advantage Of ORM
--------------------
1. Productivity : Developers more concentrate on the business logic and increase the project’s productivity by  rid of writing complex and tedious SQL statement,

2. Maintainability :  helps to reduce the lines of code as a result more easier to refactor.

3. Portability : witching to other SQL database requires few changes in Hibernate configuration file.

4  Caching : Caching  feature  reduced round trips between an application and the database

4. What are the core interfaces of Hibernate framework?
--------------------------------------------------------
1. Session Interface:  Light weight and a non-threadsafe object that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and
closed when all work is complete.

2. SessionFactory interface: SessionFactory is threadsafe responsible for creating session on request from the application.  Usually an application has a single
SessionFactory instance

3. Configuration Interface: Allows the application to specify properties and mapping documents to be used when creating a SessionFactory.

4. Transaction Interface: provide support for JDBC transaction, JTA transaction.

Query and Criteria Interface : This interface allows the user to perform queries and also control the flow of the query execution.


5. Explain hibernate object states? Explain hibernate objects life cycle?
-------------------------------------------------------------------------
Transient : An object instantiated using the "new" operator which is not associated with any session in hibernate is said to be in Transient state.

Persistent : A persistent instance has a representation in the database and an identifier value. associated with any session.

Detached :  A detached instance is an object that has been persistent, but its Session has been closed hence no longer associated with a session.

life cycle:

When we create an object of our pojo class ,we can say it is in Transient state. At the time of Transient state any modification does not affect database table. If no longer referenced by any other object, it refer to garbage collection.

When you save transient object it enter into persistent state. Persistent instance has valid database table row with a primary key identifier .

The persistent object is still exist after closure of the active session is detached object. It is still represents to the valid row in the database. Can reattach detached

Removed State :
When the persistent object is deleted from the database. At this state java instance exist but any changes made to the object are not saved to the database.



6. When does an object become detached?
---------------------------------------------------
Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId);      //”myCar” is a persistent object at this stage.
session1.close();   

 it can be reattached to another session as shown below:

Session session2 = sessionFactory.openSession();
Transaction tx = session2.beginTransaction();
session2.update(myCar);            //detached object ”myCar” gets re-attached
tx.commit();                       //change is synchronized with the database.
session2.close()



7. How does Hibernate distinguish between transient and detached objects?
-------------------------------------------------------------------------------------------
Hibernate uses the "version" property, if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. Write own strategy with Interceptor.isUnsaved().



8. What are the benefits of detached objects?
-----------------------------------------------------
Detached objects can be reattached to another session. need to make sure that the dependent objects are reattached as well.


9. What is the difference between sorted and ordered collection in hibernate?
-----------------------------------------------------------------------------
Sorted Collection is sorting a collection by utilizing the sorting  features provided by the Java collections framework using java comparator.

Order Collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.



10. What are the Collection types in Hibernate ?
----------------------------------------------------
Bag
Set
List
Array
Map


11. What is the difference between the session.get() method and the session.load() method?
---------------------------------------------------------------------------------------
Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.


12.What is the difference between the session.update() method and the session.lock() method?
-----------------------------------------------------------------------------------------
Both update() and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database.Use session.lock() only if you are absolutely sure that the detached object is in sync.



13. How would you reattach detached objects to a session when the same object has already been loaded into the session?
-------------------------------------------------------------------------------------------------------------------
use the session.merge() method call.

14. What are different of caches in Hibernate
------------------------------------------------------
Hibernate uses two different caches

First-Level cache : Associated with the Session object. Hibernate uses this cache by default on per-transaction basis to reduce the  number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction.


Second-level cache : Associates with the Session Factory as result available to whole application rather than any particular session. Improve performance by saving few database round trip.By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.


 Hibernate configuration:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

15. How does the hibernate second-level cache work?
------------------------------------------------------------------
Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database.

16. What is query cache in Hibernate ?
----------------------------------------------
Query Cache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries.

Example:
final Order customer = ... ;
final String hql = "from Order as order where order.cusomer.id = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer.getId());
q.setCacheable(true);
       
 Hibernate configuration:
<property name="hibernate.cache.use_query_cache">true</property>       

17. What are the different  cache concurrency strategy:
---------------------------------------------------------------
Read-only : This strategy is useful for data that is read frequently but  never updated.

Read-write : appropriate if your  data needs to be updated. They carry more overhead than read-only  caches.

Nonstrict-read-write:  This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes

Transactional : This is a fully transactional cache that may be used only in a JTA environment.

18. What are the different fetching strategy in Hibernate :
---------------------------------------------------------------------

Join Fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

Select Fetching:  A second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy=”false”, this second select will only be executed when you access the association.

Subselect fetching: A second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifyinglazy=”false”, this second select will only be executed when you access the association.

Batch fetching: Using primary or foreign keys hibernate retrieves a batch of entity instances or collections in a single SELECT.

19. What do you understand by automatic dirty checking in Hibernate?
-----------------------------------------------------------------------------------
Dirty checking concept :
Dirty checking is a concept to avoid time consuming database write actions. By this concept, all necessary updating and changes are done without affecting the other fields.Only the changed fields of database are updated and the remaining unchanged fields are left untouched.

Hibernate Dirty Checking :

Hibernate allows dirty checking feature. It saves developer's time and effort in updating of database when states of objects are modified inside a transaction.Hibernate automatically detects the object states whenever changed and synchronized with the database in order to update.

20. What session.flush() do
------------------------------------
Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database.By default, Hibernate will flush changes automatically

21. What is version checking in Hibernate ?
-----------------------------------------------------
Version checking used in hibernate when more then one thread trying to access same data.Optimistic locking using the version attribute

22. Optimistic vs. Pessimistic Locking
-------------------------------------------

Optimistic locking assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check
reveals conflicting modifications, the committing transaction rolls back.

Pessimistic locking assumes that concurrent transactions will conflict with each other, and requires resources to be locked after they are read and only unlocked after the application has finished using the data.

23. Why it's important to provide no argument constructor in Hibernate Entities?
----------------------------------------------------------------------------
Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API,

24. Can we make an Hibernate Entity Class final?
--------------------------------------------------
Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy



25. What is HQL ?
----------------------
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database

26. What is lazy fetching in hibernate ? 
------------------------------------------
Lazy fetching is associated with child objects loading for its parents.  While loading the parent, the selection of loading a child object is to  be specified / mentioned in the hbm.xml file. Hibernate does not load  the whole child objects by default. Lazy=true means not to load the child objects.


27. What are derived properties?
--------------------------------------------
The properties that are not mapped to a column, but calculated and evaluated at runtime called derived properties.JPA doesn't offer any support for derived property

example
    @Formula("PRICE*1.155")
    private float finalPrice;
    @Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
    private Date firstOrderDate;
    or
   
    <property name="finalPrice"   formula="PRICE*1.155"   type="date" />
    <property name="firstOrderDate"   formula="select min(o.creation_date) from Orders o where o.customer_id = id"   type="date" />
   
   
28.  What are the ways to express joins in HQL?
--------------------------------------------------------
HQL provides four ways of  expressing (inner and outer) joins:-

An implicit association join : from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten

join in the FROM  clause : from Cat as cat  inner join fetch cat.mate  left join fetch cat.kittens child  left join fetch child.kittens

theta-style join in the WHERE clause.
    
29. What are the types of inheritance models  in Hibernate?
---------------------------------------------------------------------
There are three types of inheritance models in Hibernate:

Table per class hierarchy
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(    name=""discriminator"",    discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value=""P"")    

Table per subclass 
@Inheritance(strategy=InheritanceType.JOINED)     

Table per concrete class
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

No comments:

Post a Comment

AWS Services

      1.         Identity Access Management (IAM): Used to control Identity (who) Access (what AWS resources).                   1....