Case Study

O/R Mapping

Previous Next
The case study uses Hibernate for object-relational mapping. The mapping file for the Product class is shown below. Each class of the domain model uses a generated identifier. The HQL for the finder methods is contained in the mapping file. Product.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.springunit.framework.samples.jpetstore.domain">
	<class name="Product" table="PRODUCTS" lazy="false">
		<id name="id" column="ID">
			<generator class="native"/>
		</id>
		<many-to-one name="category" column="CATEGORY" class="Category" not-null="true"/>
		<property name="name" column="NAME" length="32"/>
		<property name="description" column="DESCRIPTION" length="80"/>
	</class>
	<query name="Product.findAll">
		<![CDATA[
		from Product
		]]>
	</query>
	<query name="Product.findByCategoryName">
		<![CDATA[
		from Product p where p.category.name = :name
		]]>
	</query>
	<query name="Product.findLikeKeywords">
		<![CDATA[
		from Product p where p.description like :keywords
		]]>
	</query>
</hibernate-mapping>
AbstractHibernateSpringDao contains a HibernateDaoSupport object, which itself contains an instance of Spring's HibernateTemplate. HibernateTemplate provides findByNamedQueryAndNamedParam, which obtains the HQL from the Hibernate mapping file. AbstractHibernateSpringDao.java (excerpt)

	protected List<? extends V> findByNamedQueryAndNamedParam(
			String queryName, String paramName, Object value) {
		return (List<? extends V>)this.delegate.getHibernateTemplate().findByNamedQueryAndNamedParam(
				queryName, paramName, value);
	}

	protected List<? extends V> findByNamedQueryAndNamedParam(
			String queryName, String[] paramNames, Object[] values) {
		return (List<? extends V>)this.delegate.getHibernateTemplate().findByNamedQueryAndNamedParam(
				queryName, paramNames, values);
	}

	protected HibernateDaoSupport delegate;

The finder methods in the DAO classes, such as ProductDaoHibernate, delegate to the findByNamedQueryAndNamedParam method of the superclass AbstractHibernateSpringDao, passing in the name of the query, name of the parameter, and value of the parameter. ProductDaoHibernate.java (excerpt)
	
	public List<? extends V> getProductListByCategoryName(String name) {
		return findByNamedQueryAndNamedParam(
			"Product.findByCategoryName", "name", name);
	}

	public List<? extends V> searchProductList(String keywords) throws DataAccessException {
		return findByNamedQueryAndNamedParam(
				"Product.findLikeKeywords", "keywords", keywords);
	}


Previous Next