Skip to content

Spring Hibernate Annotation Criteria Query Example

I’ve written the start of another data load updating framework. This time I’m using Spring, Hibernate, and Hibernate Annotations.

It took a little tweaking to get this to work, and so I’ve decided to add my example in the hopes that this will help others get started quickly. This is a very basic example but I think it’s a good start. I’ve referenced sites I found to implement this at the end.

Here’s my spring config, detailing the datasource, the annotationbeanfactory, and dao.

<?xml version="1.0" encoding="UTF-8" ?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory">
			<ref bean="targetSessionFactory"/>
		</property>
	</bean>

	<bean id="targetSessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource">
			<ref bean="targetSource"/>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
				<prop key="show_sql">true</prop>
				<prop key="format_sql">true</prop>
				<!-- >prop key="hbm2ddl.auto">create</prop -->
			</props>
		</property>
		<property name="annotatedClasses">
			<list>
				<value>revert.to.console.store.model.ShortList</value>
			</list>
		</property>
	</bean>

  	<bean id="targetSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName">
			<value>${target.driver}</value>
		</property>
		<property name="url">
			<value>${target.url}</value>
		</property>
		<property name="username">
			<value>${target.username}</value>
		</property>
		<property name="password">
			<value>${target.password}</value>
		</property>
	</bean>

	<bean id="shortListDao" class="revert.to.console.store.dao.ShortListDaoHibernate">
		<property name="hibernateTemplate">
			<ref bean="hibernateTemplate"/>
		</property>
	</bean>
</beans>

Here is my ShortList Annotated POJO:

package revert.to.console.store.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**
 * @author eceppda
CREATE TABLE shortlist (
  shortlist_seq NUMBER(10,0) NOT NULL,
  record_version                 NUMBER(10,0) NOT NULL,
  concept_seq           NUMBER(10,0) NOT NULL,
  "TYPE"                           VARCHAR2(50) NOT NULL,
  "NAME"                           VARCHAR2(50) NOT NULL,
  newSpecialty                      VARCHAR2(50) NULL,
)
 */
@Entity
@Table(name="SHORTLIST")
public class ShortList{

	private int shortListSeq, conceptSeq, recordVersion,;
	private String type, name, newSpecialty;

	@Column(name="CONCEPT_SEQ")
	public int getConceptSeq() {
		return conceptSeq;
	}
	public void setConceptSeq(int conceptSeq) {
		this.conceptSeq = conceptSeq;
	}

	@Id
	@GenericGenerator( name = "hibseq", strategy = "hilo" )
	@Column(name="SHORTLIST_SEQ")
	public int getShortListSeq() {
		return shortListSeq;
	}
	public void setShortListSeq(int shortListSeq) {
		this.shortListSeq = shortListSeq;
	}
	@Column(name="NAME")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name="NEW_SPECIALTY")
	public String getNewSpecialty() {
		return newSpecialty;
	}
	public void setNewSpecialty(String newSpecialty) {
		this.newSpecialty = newSpecialty;
	}
	@Column(name="TYPE")
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}

	@Column(name="RECORD_VERSION")
	public int getRecordVersion() {
		return recordVersion;
	}

	public void setRecordVersion(int recordVersion) {
		this.recordVersion = recordVersion;
	}

}

My Dao extends HibernateDaoSupport, and I execute my Criteria search like so:

	public List getMatches(Object shortList ) {
		return (List)getHibernateTemplate().execute(
				new ShortListHibernateCallback((ShortList)shortList) );
	}

I use the HibernateCallback interface to manage the session, and create my own class to pass in the variable I need to provide for a useful criteria query. The class is very simple:

/**
 *
 */
package revert.to.console.store.dao;

import java.sql.SQLException;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import revert.to.console.store.model.ShortList;

/**
 * @author eceppda
 *
 */
public class ShortListHibernateCallback implements HibernateCallback {

	private ShortList shortList;

	public ShortListHibernateCallback( ShortList shortList ) {
		this.shortList = shortList;
	}

	public Object doInHibernate(Session session) throws HibernateException,
			SQLException {
		Criteria criteria = session.createCriteria(ShortList.class);
		criteria.add(Restrictions.eq("name", "Revert to Console"));
		criteria.add(Restrictions.eq("conceptSeq", shortList.getConceptSeq()));
		criteria.add(Restrictions.eq("newSpecialty", shortList.getNewSpecialty()));
		return criteria.list();
	}
}

And that’s about all there is to it.

References:
The Hibernate Documentation provides a lot of useful information about Criteria searching, which I like because of it’s very OO approach.

I ran into some session issues before realizing I needed to use the HibernateCallback interface.

I also tried to annotate a superclass in an initial example, which presented me with a “not mapped” issue similar to this. Don’t put annotations in a super class and you won’t run into this problem.

This seems like another good approach worth mentioning.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

4 Comments

  1. Tobi wrote:

    Thanks so much for posting this example!!

    Tuesday, October 20, 2009 at 8:33 pm | Permalink
  2. Omprakash wrote:

    Perfect example. Thanks a lot dude.

    Code here with out extending HibernateDaoSupport :
    public List getClosedCountbyCriteria(Object claim ) {
    return (List)hibernateTemplate.executeFind(new ClaimCriteria((Claim)claim) );
    }

    Thursday, April 8, 2010 at 11:21 pm | Permalink
  3. Omprakash wrote:

    in above comment replace List with List less_than_symabol Claim greater_than_symbol

    Thursday, April 8, 2010 at 11:23 pm | Permalink
  4. Dipesh Dangol wrote:

    Thanks for the tutorial. It is really great.

    Wednesday, September 28, 2011 at 12:54 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*