Notes on Spring and Hibernate

Q# How do you implement transaction handling in spring and hibernate?

This looks like a very good explanation of spring and hibernate transaction handling:
http://java.dzone.com/articles/spring-hibernate-persistence
It first discusses hibernate the traditional way, using session etc.then describes hibernate using spring templates.
With Spring, you do not need to implement code for obtaining Session objects, starting and committing transactions, and handling Hibernate exceptions. Instead, you use a HibernateTemplate instance to delegate persistence calls to Hibernate, without direct interaction with Hibernate.
This page would clear any questions about spring/hibernate including transaction handling, etc.
Also
http://static.springsource.org/spring/docs/2.0.8/reference/transaction.html
Spring declarative transaction types
@Transactional
Enum Constants
Enum Constant and Description
MANDATORY
Support a current transaction, throw an exception if none exists.
NESTED
Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER
Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED
Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED
Support a current transaction, create a new one if none exists.
REQUIRES_NEW
Create a new transaction, and suspend the current transaction if one exists.
SUPPORTS
Support a current transaction, execute non-transactionally if none exists.

JDBC is a Java standard for database connection. JPA isolates the Java developer from the inner workings of JDBC and database operations. Hibernate, EclipseLink, OpenJPA and Data Nucleus are famous JPA implementations. JTA is a standard for transactions, allowing for management of multiple transactions among multiple databases. JPA utilizes JDBC for database connections and SQL-related operations, and -optionally- utilizes JTA for delegating distributed transaction management details to it.

Q# How does hibernate implement caching programatically?

There are two types of caching – first-level and second-level. First-level cache is hibernate’s internal cache that it uses for optimizing. Second-level caching, is what we normally refer to as caching generally. Secondary level caching is usually implemented using an algorithm like Least Recently Used algorithm.
From
http://www.informit.com/articles/article.aspx?p=353736&seqNum=5
By storing the data in a cache instead of relying solely on the database, you may be able to significantly reduce the load on the database, and possibly to increase overall performance as well.
From
http://cuppajavamattiz.com/2010/07/30/hibernate-ehcache-and-caching/
First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly 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, containing all the modifications.
To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.

Implementing caching programatically
We specify which classes to cache and the caching params but we don’t really write code to invoke the cache.
http://www.informit.com/articles/article.aspx?p=353736&seqNum=5 #Configuring a Cache.
If you feel certain that the problems are due to the amount of traffic between your application and the database. The solution in this case may be a cache. By storing the data in a cache instead of relying solely on the database, you may be able to significantly reduce the load on the database, and possibly to increase overall performance as well.
Regardless of which cache you choose, you will need to tell Hibernate what sort of cache rules should be applied to your data. This is defined using the cache tag. You can place the cache tag in your *.hbm.xml files or in the hibernate.cfg.xml file. Alternatively, you can configure cache settings programmatically using the Configuration object.

Q# How do you configure hibernate using spring?

Hibernate Integration with Spring http://java.dzone.com/articles/spring-hibernate-persistence
http://elope.wordpress.com/2007/09/06/difference-between-jpa-and-hibernate/
When the application uses hibernate using hibernate.cfg.xml, the Session Factory configured through it is available to the DAO class.

SessionFactory sessionFactory =new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Transaction tx = sesssion.beginTransaction();
Object obj = session.get(....);
session.createQuery("HQL_query");
tx.commit();
session.close();

Spring’s Hibernate Support
The datasource is configured in Spring’s application context xml. The datasource might be configured using a JNDI context as well. Spring provides support for hibernate through the HibernateDaoSupport class. The HibernateDao support wraps the HibernateTemplate which in turn wraps the Hibernate session object which in turn wraps the Hibernate Session Factory. The session factory is passed a reference to the configured datasource in the spring context. The hibernate template is an abstraction around the usual boilerplate code written when only hibernate is used; and takes care of managing transactions, handling exceptions, managing connections and delegating persistence calls to hibernate. save(), load(), get(), which is invoked on the hibernate session, can be invoked on the hibernate template as well, in addition to find() and findByCriteria() not exposed by the hibernate session.
Spring’s IOC layer also allows the DAO class to be loosely coupled from the service layer and be configured through xml files. In a spring application, the dao layer is usually separated from the business layer by a service facade pattern. Transaction management can be done decoratively instead of code.
When you use JPA with Spring the underlying Hibernate or EJB3 implementation of the persistence layer is hidden and JPA act as a wrapper over them.

The DAO class(Spring) is a wrapper over HibernateTemplate(Spring) which in turn wraps the Hibernate session object which in turn wraps the Hibernate Session Factory. Obtain session from sessionfactory, open transaction from session, commit/ rollback the transaction and close the session. Get hibernateTemplate(Spring) from SessionFactory(Hibernate) to perform the perisistence operations. Don’t work directly with session in Spring. Spring obtains instances of Session objects from the SessionFactory instance. Exceptions emerging from Hibernate are handled by the Spring layer and transactions can be managed if required declaratively by the Spring layer.

Q# Explain lazy loading and eager fetch in hibernate.

If object A has relation with object B, if you load object A, object B is not loaded from db automatically; it will be loaded only when you do getB(). Eager fetch is the opposite technique. In eager fetch B is loaded when A is loaded if A contains B. The default mechanism is lazy loading.
When to use lazy loading and when to use eager fetch:
Lazy load will not automatically load child objects. It will load child objects only when getChild() is called. Eager fetch will automatically load child objects when the parent object is loaded.
Whether to use lazy load or eager fetch depends on your performance requirements.
If you use eager fetch children were already loaded and are already in memory so accessing these objects will be faster. Memory consumption will be more because more objects are in memory even if they are not needed.If you use lazy load, child objects are loaded only when required (when getter method is invoked). Hence accessing child objects will be somewhat slower but will use lesser memory since objects are loaded only if they are required.
http://powerdream5.wordpress.com/2007/11/09/eager-loading-in-hibernate/

Q# Give some advantages of JPA over hibernate. When do we use hibernate and when do we use JPA?

JPA is a wrapper around ORM technology such as EJB3 and Hibernate among others.
Hibernate 3.0 as well as EJB3 implement and support JPA. Code written using JPA uses a standard Java API so that it is generic and implementation agnostic. I could switch hibernate to use something else like iBatis etc. Beneath JPA, the underlying persistence mechanism could be hibernate or toplink or jbatis etc. JPA delegates the database transactions to the underlying persistence layer. The underlying persistence mechanism could be changed anytime and the JPA code wouldn’t change.

And hibernate 3.0 implements the JPA specification so TopLink and other O/R mapping framework.So your code depends upon JPA Api and its implementation is supplied by any JPA impl vendor framework. So in effect if you use JPA , you are using a standard Java Api and not some orthogonal Api and hence you have flexibility in your system. Say initially you have used Hibernate but now want to shift to Other framework.That means JPA supports pluggable persistence providers. JPA specification is heavily influenced by current O/R mapping frameworks like Hibernate and Top-Link.

Q# What is cascade-all in Hibernate? What are its advantages?

In a hibernate mapping file, if you specify cascade=”none” means that saving or deleting first hibernate object has no affect on related object. cascade=”save” means if first object is saved it automatically saves the related object. Similarly cascade delete will delete related object. cascade=”all” is everything save, delete etc even if they are related with foreign keys. The FK constraints etc. everything gets deleted and hibernate takes care of that.
eg.
The code to add a Child looks like this

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.save(c);
session.flush()

You can address the frustrations of the explicit call to save() by using cascades.

Cascade in hibernate (saving child objects as well) and cascade in sql(deleting rows in parent table when fk related child tables rows are deleted)

Q# What is dirty checking in hibernate? What are its advantages?

Dirty checking is hibernate is an internal mechanism that ensures that the value of the hibernate POJO object matches what is in the database(synchronizes). If the value does not match it is said to be “dirty” and hence value is refreshed from the database. Hibernate updates only “dirty” objects – only objects that have changed. Hibernate keeps track of which objects are dirty and occasionally “flushes” to ensure the objects are in sync with the db. The advantages of dirty checking is if hibernate doesn’t keep track of which objects are dirty it would have to update all objects that were loaded even if they didn’t change at the final commit of the transaction.

What are bean scopes in Spring?

1. singleton(default*)
Scopes a single bean definition to a single object instance per Spring IoC container.
2. prototype
Scopes a single bean definition to any number of object instances.
3. request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
4. session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
5. global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Difference between a Java singleton and a Spring singleton

The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.
Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it.
In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept.
In summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.

Advertisements

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: