SringSring

Friday, 10 July 2015

Hibernate Configuration quetions.

1) Hibernate session thread safety?
2) Hibernate Cache  & TRANSACTION Properties.
        Cache Properties
----------------
hibernate.cache.provider_class: This shows the class name of custom CacheProvider. Example org.hibernate.cache.EhCacheProvider.
hibernate.cache.use_query_cache: It is used to enables the query cache, individual queries still have to be set chacheable.
Possible values are true or false.
hibernate.use_second_level_cache: It may be use to completely disable the second level cache, which is enabled by default for classes
 which specify a <cache> mapping. The possible values are true or false.
Transaction Properties
        ----------------
hibernate.transaction.factory_class: The statement of a TransactionFactory to use with hibernate transaction API.
jta.UserTransaction:  A JNDI name used by JTA TransactionFactory to obtain the JTA UserTransaction from the application server.
        hibernate.transaction.manager_lookup_class:  The classname of a TransactionManagerLookup required when JVM-level caching is enabled or
                                           when using hilo generator in a JTA environment.
        hibernate.transaction.flush_before_completion: If enabled, the session will be automatically flushed during the before completion
                                               phase of the transaction. The possible values are true or false.
        hibernate.transaction.auto_close_session:   If enabled, the session will be automatically closed during the after completion phase of the transaction.   Possible values are true or false.

Data Source Properties
-----------------------
hibernate.connection.datasource: This property is used to represent datasource JNDI name.
hibernate.jndi.url: It denotes the URL of the JDNI provider.It is optional.
hibernate.jndi.class: It denotes the class of the JNDI InitialContextFactory. It is also optional.
hibernate.connection.usrname: It denotes the database user name.
hibernate.connection.password: It denotes the database user password.


3)What is Lazy Loading ?

Lazy loading decides whether to load the child objects while loading the parent object.
we need to do this setting in Hibernate mapping files(hbm.xml) of parent class
lazy =true ,(means not to load child object).  Default value is true,

This make sure that the child objects are not loaded unless they are explicitly invoked in application by calling getChild() method on parent.
In this case hibernate issues a fresh Database call to load the child objects when getChild() method actually called on the parent object.

but some cases we need to load the child objects when parent is loaded, just make the lazy=false this is called Agressive Loading.
i.e Hibernate will  load the child object when parent is loaded from the database.


4)  What is cascading

Cascading is the process of applying the operation happen on the parent to all the childs.

ex: If we apply the delete cascade operation then when parent object is deleted all the associated child objects will be deleted automatically.
Possible values are :----    all ,|none,save-update,delete,all-delete-orphan

Default value is none.


eg: Set<Long> phones; <set name="phones" table="phones" cascade="delete"></set>

5) Understanding hibernate first level cache with example.

   Caching is a facility provided by ORM frameworks which help users to get fast running web application, while help framework itself to reduce number of queries made to database in a single transaction. Hibernate achieves the second goal by implementing first level cache.
 
   Fist level cache in hibernate is enabled by default and you do not need to do anything to get this functionality working. In fact, you can not disable it even forcefully.

Its easy to understand the first level cache if we understand the fact that it is associated with Session object. As we know session object is created on demand from session factory and it is lost, once the session is closed. Similarly, first level cache associated with session object is available only till session object is live. It is available to session object only and is not accessible to any other session object in any other part of application.

Important facts
    ------------------
1) First level cache is associated with “session” object and other session objects in application can not see it.
2)  The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
3)  First level cache is enabled by default and you can not disable it.
4)  When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.
    5)  If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
    6)  The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method.
    7) The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

6) Hibernate EhCache configuration tutorial?
    Caching is facility provided by ORM frameworks which help users to get fast running web application, while help framework itself to reduce number of queries made to database in a single transaction. Hibernate also provide this caching functionality, in two layers.
   Fist level cache: This is enabled by default and works in session scope. Read more about hibernate first level cache.
Second level cache: This is apart from first level cache which is available to be used globally in session factory scope.
In this tutorial, I am giving an example using ehcache configuration as second level cache in hibernate.


How second level cache works?
-------------------------------
    Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache
(associated with particular hibernate session).
    If cached copy of entity is present in first level cache, it is returned as result of load method.
    If there is no cached entity in first level cache, then second level cache is looked up for cached entity.
    If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again.
    If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.
Second level cache validate itself for modified entities, if modification has been done through hibernate session APIs.
If some user or process make changes directly in database, the there is no way that second level cache update itself until “timeToLiveSeconds” duration has passed for that cache region. In this case, it is good idea to invalidate whole cache and let hibernate build its cache once again. You can use below code snippet to invalidate whole hibernate second level cache.



Configuring EhCache

To configure ehcache, you need to do two steps:

configure Hibernate for second level caching
specify the second level cache provider
Hibernate 3.3 and above
---------------------------------
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
Hibernate 3.2 and below
---------------------------------
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>

Configuring entity objects
----------------------------------
        This may done in two ways.

1) If you are using hbm.xml files then use below configuration:

<class name="com.application.entity.DepartmentEntity" table="...">
<cache usage="read-write"/>
</class>
2) Otherwise, if you are using annotations, use these annotations:

@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="department")
public class DepartmentEntity implements Serializable
{    //code }

For both options, caching strategy can be of following types:

none : No caching will happen.
read-only : If your application needs to read, but not modify, instances of a persistent class, a read-only cache can be used.
read-write : If the application needs to update data, a read-write cache might be appropriate.
nonstrict-read-write : If the application only occasionally needs to update data (i.e. if it is extremely unlikely that two transactions would try to update the same item simultaneously), and strict transaction isolation is not required, a nonstrict-read-write cache might be appropriate.
transactional : The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache can only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class.

Query caching
        --------------
You can also enable query caching. To do so configure it in your hbm.xml:

<property key="hibernate.cache.use_query_cache">true</property>
and where queries are defined in your code, add the method call setCacheable(true) to the queries that should be cached:

sessionFactory.getCurrentSession().createQuery("...").setCacheable(true).list();
By default, Ehcache will create separate cache regions for each entity that you configure for caching. You can change the defaults for these regions by adding the configuration to your ehcache.xml. To provide this configuration file, use this property in hibernate configuration:

<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
And use below configuration to override the default configuration:

<cache
    name="com.somecompany.someproject.domain.Country"
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="300"
    timeToLiveSeconds="600"
    overflowToDisk="true"
/>

1 comment: