07 Nov
07Nov
What’s Hibernate?
Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.
 What is ORM?
ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.
 How properties of a class are mapped to the columns of a database table in Hibernate?
Mappings between class properties and table columns are specified in XML file as in the below example:
What’s the usage of Configuration Interface in hibernate?
Configuration interface of hibernate framework is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.
How can we use new custom interfaces to enhance functionality of built-in interfaces of hibernate?
We can use extension interfaces in order to add any required functionality which isn’t supported by built-in interfaces.
Should all the mapping files of hibernate have .hbm.xml extension to work properly?

No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping file names. We can have any extension for these mapping files.

How do we create session factory in hibernate?

To create a session factory in hibernate, an object of configuration is created first which refers to the path of configuration file and then for that configuration, session factory is created as given in the example below:

1

2

3

4

Configuration config = new Configuration();

config.addResource("myinstance/configuration.hbm.xml");

config.setProperties( System.getProperties() );

SessionFactory sessions = config.buildSessionFactory();


What are POJOs and what’s their significance?
POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.
What’s HQL?
HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.
How can we invoke stored procedures in hibernate?

What is criteria API?
Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.
What are the benefits of using Hibernate template?
Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.
How can we see hibernate generated SQL on console?

We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:


What are the two types of collections in hibernate?
Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection
What’s the difference between session.save() and session.saveOrUpdate() methods in hibernate?
Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.
What the benefits are of hibernate over JDBC?
a. Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.
How can we get hibernate statistics?
We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()
What is transient instance state in Hibernate?
If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.
How can we reduce database write action times in Hibernate?
Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.
What’s the usage of callback interfaces in hibernate?
Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.
When an instance goes in detached state in hibernate?
When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.
 What the four ORM levels are in hibernate?
Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping
What’s transaction management in hibernate? How it works?

Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:

1

2

3

4

5

6

7

8

9

10

11

12

Session s = null;

Transaction tr = null;

try {

s = sessionFactory.openSession();

tr = s.beginTransaction();

doTheAction(s);

tr.commit();

} catch (RuntimeException exc) {

tr.rollback();

} finally {

s.close();

}



What the two methods are of hibernate configuration?
We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)
What is the default cache service of hibernate?
Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.
What are the two mapping associations used in hibernate?
In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association
What’s the usage of Hibernate QBC API?
Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.


In how many ways, objects can be fetched from database in hibernate?
Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL
How primary key is created by using hibernate?
Database primary key is specified in the configuration file hbm.xml. Generator can also be used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:

How can we reattach any detached objects in Hibernate?
Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.
What are different ways to disable hibernate second level cache?
Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider
What is ORM metadata?
All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.
Which one is the default transaction factory in hibernate?
With hibernate 3.2, default transaction factory is JDBCTransactionFactory.
What’s the role of JMX in hibernate?
Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.
How can we bind hibernate session factory to JNDI ?
Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.
In how many ways objects can be identified in Hibernate?
Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.
What different fetching strategies are of hibernate?
Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching
How mapping of java objects is done with database tables?

To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:



What are derived properties in hibernate?
Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.
 What is meant by a Named SQL Query in hibernate and how it’s used?

Named SQL queries are those queries which are defined in mapping file and are called as required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:

Then this query can be called as follows:

Java

1

2

3

4

List students = session.getNamedQuery("studentdetails")

.setString("TomBrady", name)

.setMaxResults(50)

.list();


What’s the difference between load() and get() method in hibernate?
Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.
What’s the use of version property in hibernate?
Version property is used in hibernate to know whether an object is in transient state or in detached state.
 What is attribute oriented programming?
In Attribute oriented programming, a developer can add Meta data (attributes) in the java source code to add more significance in the code. For Java (hibernate), attribute oriented programming is enabled by an engine called XDoclet.
What’s the use of session.lock() in hibernate?
session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.
Does hibernate support polymorphism?
Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.
What the three inheritance models are of hibernate?
Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class
How can we map the classes as immutable?
If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false
What’s general hibernate flow using RDBMS?
General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.
What is Light Object Mapping?
Light Object Mapping is one of the levels of ORM quality in which all entities are represented as classes and they are mapped manually.
What’s difference between managed associations and hibernate associations?
Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.
Can you define the types of collection in Hibernate?
There are five types of collections -
 
1.      Map
2.      Array
3.      List
4.      Set
5.      Bag
What is your understanding of Hibernate proxy?
The classes in Hibernate can be mapped as a proxy rather than a table. A proxy can be returned when the load in a session is called. Proxy comprises methods to load data. A proxy is often created for mapping classes to files.
What according to you are the cache types in Hibernate?
Hibernate deploys two caches with respect to objects. These are 1) First Level Cache  2) Second Level Cache. The first case is related to session object, and the second is related to SessionFactory. Hibernate, by default, uses the first on the basis of per-transaction. This cache is mainly used by Hibernate to lessen the SQL query numbers that need to be generated within a specific transaction.

What is Hibernate Caching?

Caching is every about request performance optimization and it sits between your application and the database to avoid the number of database hits as several as possible to give a better performance for presentation essential applications.

Whenever same request is made for same data mulitple times then instead of hitting the database multiple times we hit the cache memory.

Caching is main to Hibernate as well which utilizes multilevel caching schemes as explained below:
hibernate_cache

First-level cache:

The first-level cache is the Session cache and is an optional cache through which all desires must pass. The Session object keeps an entity under its own power before commit it to the database.

If you subject multiple updates to an object, Hibernate tries to hold-up doing the update as long as possible to decrease the number of update SQL statements issued. If you secure the session, all the objects being cached are lost and either persisted or updated in the database.

Second-level cache:

Second level cache is an optional cache and first-level cache will always be consult before any attempt is made to locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-collection basis and mainly in charge for caching objects across sessions.

Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider line is provided, which must be implemented to supply Hibernate with a handle to the cache execution.

Query-level cache:

Hibernate also equipment a cache for query result sets that integrate directly with the second-level cache.

This is a possible feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run normally with the same parameters.

The Second Level Cache:

Hibernate uses first-level cache by defaulting and you have nothing to do to use first-level cache. Let's go straight to the optional second-level cache. Not all module benefit from caching, so it's important to be able to disable the second-level cache.

The Hibernate second-level cache is set up in two steps. First, you have to choose which concurrency strategy to use. After that, you configure cache termination and physical cache attributes using the cache contributor.

Concurrency strategies:

A concurrency strategy is a moderator which accountable for storing items of data in the cache and retrieving them from the cache. If you are going to permit a second-level cache, you will have to choose, for each constant class and collection, which cache concurrency strategy to use.

  • Transactional: Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions, in the rare case of an update.
  • Read-write: Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions, in the rare case of an update.
  • Constrict-read-write: This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern.
  • Read-only: A concurrency strategy suitable for data which never changes. Use it for reference data only.
What are the benefits of ORM
  • connecting to database server .
  • generating query .
  • sanitizing the parameter if any.
  • fetching the data and serializing it if necessary .

-You don’t need any SQL knowledge to use an ORM . Considering all the pain for learning complex DMLs. Joins , sub selects , insert , multi insert and the list goes on . You can use an ORM without knowing sql at all.

-The ORM secures the query for any type of attack.


Generator Classes in Hibernate
The class is a sub-element of id. It is used to generate the unique identifier for the objects of persistent class. There are many generator classes defined in the Hibernate Framework.

All the generator  classes implements the org.hibernate.id.IdentifierGenerator interface. The application  programmer  may create one's own generator classes by implementing  the IdentifierGenerator interface. Hibernate framework provides many built-in  generator classes:

  1. assigned
  2. increment
  3. sequence
  4. hilo
  5. native
  6. identity
  7. seqhilo
  8. uuid
  9. guid
  10. select
  11. foreign
  12. sequence-identity


1) assigned

It is the default generator strategy if there is no element . In this case, application assigns the id. For example:

2) increment

It generates the unique id only if no other process is inserting data into this table. It generates short, int or long type identifier. If a table contains an identifier then the application considers its maximum value else the application consider that the first generated identifier is 1. For each attribute value, the hibernate increment the identifier by 1. 

3) sequence

It uses the sequence of the database. if there is no sequence defined, it creates a sequence automatically e.g. in case of Oracle database, it creates a sequence named HIBERNATE_SEQUENCE.  In case of Oracle, DB2, SAP DB,  Postgre SQL or McKoi, it uses sequence but it uses generator in interbase.

4) hilo

It uses high and low algorithm to generate the id of type short, int and long.

5) native

It uses identity, sequence or hilo depending on the database vendor.

6) identity

It is used in Sybase, My SQL, MS SQL Server, DB2 and HypersonicSQL to support the id column. The returned id is of type short, int or long. It is responsibility of database to generate unique identifier. 

8) uuid

It uses 128-bit UUID algorithm to generate the id. The returned id is of type String, unique within a network (because IP is used). The UUID is represented in hexadecimal digits, 32 in length.

9) guid

It uses GUID generated by database of type string. It works on MS SQL Server and MySQL.

10) select

It uses the primary key returned by the database trigger.

11) foreign

It uses the id of another associated object, mostly used with association. 


Collection Mapping in Hibernate

We can map collection elements of Persistent class in Hibernate. You need to declare the type of collection in  Persistent class from one of the following types:

  • java.util.List
  • java.util.Set
  • java.util.SortedSet
  • java.util.Map
  • java.util.SortedMap
  • java.util.Collection
  • or write the implementation of org.hibernate.usertype.UserCollectionType

There are many subelements of elements to map the collection. They are , , and . Let's see how we implement the list for the above class:


Here, List is mapped by one-to-many relation. In this scenario, there can be many answers for one question. 

Hibernate One to many mapping Annotation

Hibernate one to many mapping is made between two entities where first entity can have relation with multiple second entity instances but second can be associated with only one instance of first entity. Its 1 to N relationship.

For example, in any company an employee can register multiple bank accounts but one bank account will be associated with one and only one employee. 

Reference   :   https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/


This problem can be solved in two different ways.

  1. One is to have a foreign key column in account table i.e. EMPLOYEE_ID. This column will refer to primary key of Employee table. This way no two accounts can be associated with multiple employees. Obviously, account number needs to be unique for enforcing this restriction.
  2. Second approach is to have a common join table lets say EMPLOYEE_ACCOUNT. This table will have two column i.e. EMP_ID which will be foreign key referring to primary key in EMPLOYEE table and similarly ACCOUNT_ID which will be foreign key referring to primary key of ACCOUNT table.



 

Hibernate One to Many mapping with join table
This approach uses a join table to store the associations between account and employee entities. @JoinTable annotation has been used to make this association.


Hibernate Many to Many Mapping Design

To demonstrate many to many mapping using hibernate annotations, we will associate two entities i.e. ReaderEntity and SubscriptionEntity.

Their database schema should look like this. Using these tables, any application can save multiple associations between readers and subscriptions.

Owner entity is the entity which is responsible make making the association and maintaining it. In our case, I am making ReaderEntity the owner entity. @JoinTable annotation has been used to make this association.
🍧What is CascadeType in Hibernate
🍥one-to-one mapping and one-to-many mappings. There we wanted to save the mapped entity whenever relationship owner entity got saved. To enable this we had use “CascadeType” attribute.

Look at the bold line in above source code for EmployeeEntity.java. It defines “cascade=CascadeType.ALL” and it essentially means that any change happened on EmployeeEntity must cascade to AccountEntity as well. If you save an employee, then all associated accounts will also be saved into database. If you delete an Employee then all accounts associated with that Employee also be deleted. Simple enough.

But what if we only want to cascade only save operations but not delete operation. Then we need to clearly specify it using below code.

Now only when save() or persist() methods are called using employee instance then only accounts will be persisted. If any other method is called on session, it’s effect will not affect/cascade to accounts.

JPA Cascade Types

The cascade types supported by the Java Persistence Architecture are as below:

  1. CascadeType.PERSIST : cascade type presist means that save() or persist() operations cascade to related entities.
  2. CascadeType.MERGE : cascade type merge means that related entities are merged when the owning entity is merged.
  3. CascadeType.REFRESH : cascade type refresh does the same thing for the refresh() operation.
  4. CascadeType.REMOVE : cascade type remove removes all related entities association with this setting when the owning entity is deleted.
  5. CascadeType.DETACH : cascade type detach detaches all related entities if a “manual detach” occurs.
  6. CascadeType.ALL : cascade type all is shorthand for all of the above cascade operations.

There is no default cascade type in JPA. By default no operations are cascaded.

Hibernate Cascade Types

Now lets understand what is cascade in hibernate in which scenario we use it.

Apart from JPA provided cascade types, there is one more cascading operation in hibernate which is not part of the normal set above discussed, called “orphan removal“. This removes an owned object from the database when it’s removed from its owning relationship.

Let’s understand with an example. In our Employee and Account entity example, I have updated them as below and have mentioned “orphanRemoval = true” on accounts. It essentially means that whenever I will remove an ‘account from accounts set’ (which means I am removing the relationship between that account and Employee); the account entity which is not associated with any other Employee on database (i.e. orphan) should also be deleted.


Hibernate Entity and Persistence Life Cycles States

Given an instance of an object that is mapped to Hibernate, it can be in any one of four different states: transient, persistent, detached, or removed. We are going to learn about them today in this tutorial.

Transient Object

Transient objects exist in heap memory. Hibernate does not manage transient objects or persist changes to transient objects.

Transient objects are independent of Hibernate
Transient objects are independent of Hibernate

To persist the changes to a transient object, you would have to ask the session to save the transient object to the database, at which point Hibernate assigns the object an identifier and marks the object as being in persistent state.

Persistent Object

Persistent objects exist in the database, and Hibernate manages the persistence for persistent objects.

Persistent objects are maintained by Hibernate
Persistent objects are maintained by Hibernate

If fields or properties change on a persistent object, Hibernate will keep the database representation up to date when the application marks the changes as to be committed.

Detached Object

Detached objects have a representation in the database, but changes to the object will not be reflected in the database, and vice-versa. This temporary separation of the object and the database is shown in image below.

Detached objects exist in the database but are not maintained by Hibernate
Detached objects exist in the database but are not maintained by Hibernate

A detached object can be created by closing the session that it was associated with, or by evicting it from the session with a call to the session’s evict() method.


One reason you might consider doing this would be to read an object out of the database, modify the properties of the object in memory, and then store the results some place other than your database. This would be an alternative to doing a deep copy of the object.

In order to persist changes made to a detached object, the application must reattach it to a valid Hibernate session. A detached instance can be associated with a new Hibernate session when your application calls one of the load, refresh, merge, update(), or save() methods on the new session with a reference to the detached object. After the call, the detached object would be a persistent object managed by the new Hibernate session.

Removed Object

Removed objects are objects that are being managed by Hibernate (persistent objects, in other words) that have been passed to the session’s remove() method. When the application marks the changes held in the session as to be committed, the entries in the database that correspond to removed objects are deleted.

Now let’s not note down the take-aways from this tutorial.

Bullet Points

  1. Newly created POJO object will be in the transient state. Transient object doesn’t represent any row of the database i.e. not associated with any session object. It’s plain simple java object.
  2. Persistent object represent one row of the database and always associated with some unique hibernate session. Changes to persistent objects are tracked by hibernate and are saved into database when commit call happen.
  3. Detached objects are those who were once persistent in past, and now they are no longer persistent. To persist changes done in detached objects, you must reattach them to hibernate session.
  4. Removed objects are persistent objects that have been passed to the session’s remove() method and soon will be deleted as soon as changes held in the session will be committed to database.


🔰Hibernate First Level Cache

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.

Hibernate first level cache

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.


Second Level Cache in Hibernate
  • 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.

Above statement means, second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory.
 It also means that once session factory is closed, all cache associated with it die and cache manager also closed down.
Further, It also means that if you have two instances of session factory (normally no application does that), you will have two cache managers in your application and while accessing cache stored in physical store, you might get unpredictable results like cache-miss.

hibernate first and second level cache_example

How second level cache works

Lets write all the facts point by point:

  1. 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).
  2. If cached copy of entity is present in first level cache, it is returned as result of load method.
  3. If there is no cached entity in first level cache, then second level cache is looked up for cached entity.
  4. 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.
  5. 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.
  6. Second level cache validate itself for modified entities, if modification has been done through hibernate session APIs.
  7. 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.


ehCache Configuration

Terracotta Ehcache is a popular open source Java cache that can be used as a Hibernate second level cache. It can be used as a standalone second level cache, or can be configured for clustering to provide a replicated coherent second level cache.

Hibernate ships with the ehcache library. 

To configure ehcache, you need to do two steps:

  1. configure Hibernate for second level caching
  2. specify the second level cache provider

This may done in two ways.

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

2) Otherwise, if you are using annotations, use these annotations:

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:
and where queries are defined in your code, add the method call setCacheable(true) to the queries that should be cached:
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:
And use below configuration to override the default configuration:

Please note that in ehcache.xml, if eternal=”true” then we should not write timeToIdealSeconds, timeToLiveSeconds, hibernate will take care about those values
So if you want to give values manually better use eternal=”false” always, so that we can assign values into timeToIdealSeconds, timeToLiveSeconds manually.

timeToIdealSeconds=”seconds” means, if the object in the global cache is ideal, means not using by any other class or object then it will be waited for some time we specified and deleted from the global cache if time is exceeds more than timeToIdealSeconds value.

timeToLiveSeconds=”seconds” means, the other Session or class using this object or not, i mean may be it is using by other sessions or may not, what ever the situation might be, once it competed the time specified timeToLiveSeconds, then it will be removed from the global cache by hibernate.


Comments
* The email will not be published on the website.
I BUILT MY SITE FOR FREE USING