Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Tuesday, January 25, 2011

Spring & Hibernate Integration


SessionFactory object is Dependency-Injected
HibernateTemplate class is provided

Setting up Hibernate SesssionFactory

DataSource Setup Through DI

<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroymethod="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>product.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
</value>
</property>
</bean>
</beans>

HibernateTemplate

Helper class that simplifies Hibernate data access code
Automatically converts HibernateExceptions into DataAccessExceptions, following the org.springframework.dao exception hierarchy
The central method is execute, supporting Hibernate access code implementing the HibernateCallback interface.
● It provides Hibernate Session handling such that neither the HibernateCallback  implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions.
● For typical single step actions, there are various convenience methods (find, load, saveOrUpdate, delete).

HibernateTemplate Example

SessionFactory sessionFactory= HibernateFactory.getSessionFactory();
HibernateTemplate template= new HibernateTemplate(sessionFactory);
Event event1 = new Event("Event 1");
Event event2 = new Event("Event 2");
Event event3 = new Event("Event 3");
template.save(event1);
template.save(event2);
template.save(event3);

template.execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws
HibernateException, SQLException {
Query query = session.createQuery("from Event");
query.setMaxResults(2);
List events = query.list();
for (Iterator it = events.iterator(); it.hasNext();) {
Event event = (Event) it.next();
System.out.println(event.getName());
event.setDuration(60);
}
return null;
}
});

What Supporting Services Do We Need?

Must solve the problem of data access exceptions to have independent DAO interfaces
– Can't throw SQLException or JDOException
– Catch/warp leads to huge redundancy
Ex) Catch SQLException throw MyFunnyDaoException
– Need meaningful exceptions
Not just one SQLException
Need to be able to catch at different levels
– Data access exceptions should be unchecked

No comments:

Post a Comment