Thursday, October 15, 2009

Hibernate










Hibernate


Although we covered a lot of ground on Hibernate in Chapter 5, "Using Hibernate for Persistent Objects," there is a lot more to Hibernate, which is the very reason there are entire books written on this technology. However, a couple of other features you might find useful are discussed next.



Native SQL Queries


Most relational databases provide ANSI-SQLcompliant features; however, they also tend to go further by providing their own custom extensions, which might not be supported by HQL. To take advantage of such native SQL features, we can use Hibernate's Session.createSQLQuery method as demonstrated by the following code, which uses HSQLDB's datediff built-in function:


String sql = "select datediff(`dd', NOW, ?) AS daysleft"
+ " from timesheet";
Integer valueObject = (Integer)session.createSQLQuery(sql)
.addScalar("daysleft", Hibernate. INTEGER)
.setDate(0, DateUtil.getCurrentPeriodEndingDate())
.uniqueResult();
if (valueObject != null)
daysLeft = valueObject.intValue();





Interceptors


Interceptors, as you might guess, intercept a request. Perhaps the following description from the Hibernate reference documentation best describes the use of Hibernate interceptors: "The Interceptor interface provides callbacks from the session to the application allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. One possible use for this is to track auditing information."


To use Hibernate interceptor, we must either implement all the methods defined in the org.hibernate. Interceptor interface or alternatively, subclass the convenient org.hibernate. EmptyInterceptor concrete class and override only the methods we need to, as demonstrated by the following code excerpt.


public class AuditInterceptor extends EmptyInterceptor
{
public void afterTransactionCompletion(Transaction tx)


After we have written an interceptor class, we can either activate it for a given session using the Session.openSession(Interceptor interceptor) method or activate it at the Configuration level, as shown here:


sessionFactory = new Configuration()
.setInterceptor(new AuditInterceptor())
.configure().buildSessionFactory();













No comments:

Post a Comment