Spring Persistence with Hibernate

Spring Persistence with HibernateThis article is sample chapter taken from the book Spring persistence with Hibernate. Hibernate is a popular open-source Java framework. It aims to solve problems associated with persistence in the Java world. Whether you are developing a simple stand-alone application, or a full-blown, server-side Java EE application, you can use and benefit from Hibernate. Although Hibernate has competitors, no other persistence framework is as flexible and as easy to learn.

Spring is another popular framework. It aims to simplify Java development in many areas, including persistence. However, Spring does not provide a persistence framework similar to Hibernate. Instead, it provides an abstraction layer over Hibernate to offer more flexibility, produce more effective code, and reduce maintenance costs.

also read: follow us on @twitter and @facebook

What This Book Covers

Chapter 1, An Introduction to Hibernate and Spring introduces Spring and Hibernate, explaining what persistence is, why it is important, and how it is implemented in Java applications. It provides a theoretical discussion of Hibernate and how Hibernate solves problems related to persistence. Finally, we take a look at Spring and the role of Spring in persistence.

Chapter 2, Preparing an Application to Use Spring with Hibernate guides you, step-bystep, down the path of preparing your application to use Hibernate and Spring. The prerequisites to developing with Hibernate and Spring, including getting Hibernate and
Spring distributions, setting up a database, and adding extra tools and frameworks to your application, are all discussed here.

Chapter 3, A Quick Tour of Hibernate with Spring provides a quick tour of developing with Hibernate and Spring. Here, a simple example illustrates the basic concepts behind Hibernate and Spring.

Chapter 4, Hibernate Configuration shows you how to configure and set up Hibernate. It discusses the basic configuration settings that are always required in any application. (Some optional settings are covered in the book’s appendix.)

Chapter 5, Hibernate Mappings explains basic issues related to persistent objects and their mappings. It starts with basic mapping concepts and then moves on to advanced and practical issues.

Chapter 6, More on Mappings continues the mapping discussion with some advanced mapping topics. It explains how to map complex objects and create complicated mapping files.

Chapter 7, Hibernate Types discusses how Hibernate types help to define which Java types are mapped to which SQL database types. It explores the built-in Hibernate types. It also looks at custom type implementation when these built-in types do not satisfy the application’s requirements, or when you want to change the default behavior of a built-in type.

Chapter 8, Hibernate Persistence Behavior discusses the life cycle of persistent objects within the application’s lifetime. This chapter explains the basic persistence operations provided by the Session API at the heart of the Hibernate API. The chapter also discusses
how persistence operations are cascaded between persistent objects, and how cascading behavior is defined in mapping files.

Chapter 9, Querying in Hibernate explains the different approaches that Hibernate provides for querying persistent objects. It investigates HQL, a Hibernate-specific query language; native SQL, a database-relevant query language; and the Criteria API, a
Hibernate API to express query statements.

Chapter 10, Inversion of Control with Spring starts developing with Spring, introducing the Inversion of Control (IoC) pattern that is implemented at the heart of Spring.

Chapter 11, Spring AOP investigates Aspect-Oriented Programming (AOP) as another Spring feature. Here, you’ll learn what AOP means, how AOP simplifies application architecture, and how to implement AOP in Spring.

Chapter 12, Transaction Management discusses transaction management. It explains transaction concepts and how transactions are managed in native and Spring-based Hibernate applications. It also discusses caching as a persistence aspect that involves
reliability of data manipulation.

Chapter 13, Integrating Hibernate with Spring explains how Hibernate and Spring are integrated and introduces the Data Access Object (DAO) pattern. It shows how Spring and Hibernate combine to implement this pattern.

Chapter 14, Web Development with Hibernate and Spring provides a quick discussion of web development with Spring and Hibernate. It does not provide a detailed discussion of web development. Instead, it takes Spring and Struts as sample web frameworks to
illustrate how you might use Spring and Hibernate to develop web applications.

Chapter 15, Testing looks into testing persistence code, with a focus on unit testing. It introduces JUnit as an open-source unit-testing framework and discusses which aspects of persistence code with Hibernate require testing.

Appendix, Hibernate’s Advanced Features looks at some advanced Hibernate topics, including some useful Hibernate properties, the event/listener model implemented by Hibernate, and Hibernate filters.

Hibernate Types

Hibernate allows transparent persistence, which means the application is absolutely isolated from the underlying database storage format. Three players in the Hibernate scene implement this feature: Hibernate dialect, Hibernate types, and HQL. The Hibernate dialect allows us to use a range of different databases, supporting different, proprietary variants of SQL and column types. In addition, HQL allows us to query persisted objects, regardless of their relational persisted form in the database.

Hibernate types are a representation of databases SQL types, provide an abstraction of the underlying database types, and prevent the application from getting involved with the actual database column types. They allow us to develop the application without worrying about the target database and the column types that the database supports. Instead, we get involved with mapping Java types to Hibernate types. The database dialect, as part of Hibernate, is responsible for transforming Java types to SQL types, based on the target database. This gives us the fl exibility to change the database to one that may support different column types or SQL without changing the application code.

In this chapter, we will discuss the Hibernate types. We will see how Hibernate provides built-in types that map to common database types. We’ll also see how Hibernate allows us to implement and use custom types when these built-in types do not satisfy the application’s requirements, or when we want to change the default behavior of a built-in type. As you will see, you can easily implement a custom-type class and then use it in the same way as a built-in one.

Built-in types

Hibernate includes a rich and powerful range of built-in types. These types satisfy most needs of a typical application, providing a bridge between basic Java types and common SQL types. Java types mapped with these types range from basic, simple types, such as long and int, to large and complex types, such as Blob and Clob. The following table categorizes Hibernate built-in types with corresponding Java and SQL types:

1 3

Although the SQL types specified in the table above are standard SQL types, your database may support somewhat different SQL types. Refer to your database documentation to find out which types you may use instead of the standard SQL types shown in the table above.

Don’t worry about the SQL types that your database supports. The SQL
dialect and JDBC driver are always responsible for transforming the Java
type values to appropriate SQL type representations.

The type attribute specifies Hibernate types in mapping definitions. This helps Hibernate to create an appropriate SQL statement when the class property is stored, updated, or retrieved from its respective column.

The type attribute may appear in different places in a mapping file. You may use it with the <id>, <property>, <discriminator>, <index>, and <element> elements. Here is a sample mapping file with some type attributes in different locations:

&lt;hibernate-mapping&gt;
		&lt;class name='Person' table='PERSON' discriminator-value='PE'&gt;
			&lt;id name='id' column='ID' &lt;b&gt;type='long'&lt;/b&gt;&gt;
				&lt;generator/&gt;
			&lt;/id&gt;
			&lt;discriminator column='PERSON_TYPE' &lt;b&gt;type='string'&lt;/b&gt;/&gt;
			&lt;property name='birthdate' column='BIRTHDATE' &lt;b&gt;type='date'&lt;/b&gt;/&gt;
			&lt;list name='papers' table='STUDENT_PAPER'&gt;
				&lt;key column='STUDENT_ID'/&gt;
				&lt;list-index column='POSITION'/&gt;
				&lt;element column='PAPER_PATH' &lt;b&gt;type='string'&lt;/b&gt;/&gt;
			&lt;/list&gt;
			&lt;!-- mapping of other fields --&gt;
		&lt;/class&gt;
	&lt;/hibernate-mapping&gt;

If a property is mapped without the type attribute, Hibernate uses the refl ection API to find the actual type of that property and uses the corresponding Hibernate type for it. However, you should specify the type attribute if that property can be mapped with more than one Hibernate type. For example, if a property is of type java.lang.String, and its mapping definition does not include the type attribute, Hibernate will use the refl ection API and select the type string for it. This means you need to explicitly define the Hibernate type for a Java String if you want to map the String with a character or text Hibernate type.

Custom types

For most mappings, Hibernate’s built-in types are enough. However, in some situations, you may need to define a custom type. These situations generally happen when we want Hibernate to treat basic Java types or persistent classes differently than it normally would. Here are some situations where you may need to define and use a custom type:

  • Storing a particular Java type in a column with a different SQL type than Hibernate normally uses: For example, you might want to store a java.util.Date object in a column of type VARCHAR, or a String object in a DATE column.
  • Mapping a value type: Value types, the dependent persistent classes that do not have their own identifiers, can be mapped with custom types. This means you can treat value types similarly to primitive types and map them with the <property> element, instead of <component>. For example, the Phone class in the previous chapter was mapped with <componentgt;. You could implement custom type and use it to map Phone objects with <property>.
  • Splitting up a single property value and storing the result in more than one database column: For example, assume that any phone number is split-up into four components—representing country code, area code,
    exchange, and line number, stored in four columns of the database. We may take this approach to provide a search facility for countries, areas, exchanges, and line numbers. If the phone numbers are represented as long numbers
    populated from four columns, we need to define a custom type and tell Hibernate how to assemble the number.
  • Storing more than one property in a single column: For example, in Chapter 6, the papers property of the Student class was represented as an object of java.util.List and held the file paths of all of the papers the student has written. You can define a custom type to persist all of the papers file paths as a semicolon-separated string in a single column.
  • Using an application-specific class as an identifier for the persistent class: For example, suppose you want to use the application-specific class CustomIdentifier, instead of the int, long, String, and so on, for persistent class identifiers. In this case, you also need to implement an IdentifierGenerator to tell Hibernate how to create new identifier
    values for non-persisted objects.

In practice, other use cases also need custom types for implementation and use. In all of these situations, you must tell Hibernate how to map a particular Java type to a database representation. You do this by implementing one of the interfaces which Hibernate provides for this purpose. The basic and most commonly used of these interfaces include org.hibernate.usertype.UserType and org.hibernate. usertype. CompositeUserType. Let’s look at these in detail, discussing their differences, and how to use them.

UserType

UserType is the most commonly used Hibernate extension type. This interface exposes basic methods for defining a custom type. Here, we introduce a simple case and show how a custom type can provide a convenient mapping definition for it.

Suppose that the history of any school is represented by an individual class, History. Obviously, the History class is a value type, because no other persistent class uses the History class for its own use. This means that all History objects depend on School objects. Moreover, each school has its own history, and history is never shared between schools. Here is the School class:

package com.packtpub.springhibernate.ch07;
	import java.io.Serializable;
	public class School implements Serializable {
		private long id;
		private History history ;
		//other fields
		//setter and getter methods
		public long getId() {
			return id;
		}
		public void setId(long id) {
			this.id = id;
		}
		public History getHistory() {
			return history;
		}
		public void setHistory(History history) {
			this.history = history;
		}
		//other setters and getters
	}

And this is the History class:

	package com.packtpub.springhibernate.ch07;

	import java.io.Serializable;
	import java.util.Date;

	public class History implements Serializable {
		long initialCapacity;
		Date establishmentDate;
		public long getInitialCapacity() {
			return initialCapacity;
		}
		public void setInitialCapacity(long initialCapacity) {
			this.initialCapacity = initialCapacity;
		}
		public Date getEstablishmentDate() {
			return establishmentDate;
		}
		public void setEstablishmentDate(Date establishmentDate) {
			this.establishmentDate = establishmentDate;
		}
	}


Note that I have intentionally omitted all irrelevant fields of the two classes to keep the example simple.
Our strategy in mapping a value type so far is to use one table for persisting both the persistent class and its associated value types. Based on this strategy, we need to use a SCHOOL table, which stores all of the School and History properties, and then map both School and its History class into that table through the <component> element in the mapping file. The mapping definition for School and its associated History class is as follows:

&lt;hibernate-mapping&gt;
		&lt;class name='com.packtpub.springhibernate.ch07.School'
			table='SCHOOL'&gt;
			&lt;id name='id' type='long' column='id'&gt;
				&lt;generator/&gt;
			&lt;/id&gt;
			&lt;b&gt;&lt;component name='history'
				class='com.packtpub.springhibernate.ch07.History'&gt;
				&lt;property name='initialCapacity' column='INITIAL_CAPACITY'
					type='long'/&gt;
				&lt;property name='establishmentDate' column='ESTABLISHMENT_DATE'
					type='date'/&gt;
			&lt;/component&gt;&lt;/b&gt;
			&lt;!-- mapping of other fields --&gt;
		&lt;/class&gt;
	&lt;/hibernate-mapping&gt;

As an alternative approach, you can map the History class with a custom type. You do this by implementing a custom type, HistoryType, which defines how to map History objects to the target table. Actually, Hibernate does not persist a custom type. Instead, the custom type gives Hibernate information about how to persist a value type in the database. Let’s implement a basic custom type by implementing the UserType interface. In the next section of this chapter, we’ll discuss how to map History with an implementation of another Hibernate custom type interface, CompositeUserType.

The following code shows the HistoryType class that implements the UserType interface, providing a custom type for the History class:

package com.packtpub.springhibernate.ch07;

	import java.sql.PreparedStatement;
	import java.sql.ResultSet;
	import java.sql.SQLException;
	import java.sql.Types;
	import java.io.Serializable;
	import java.util.Date;
	import org.hibernate.Hibernate;
	import org.hibernate.HibernateException;
	import org.hibernate.usertype.UserType;

	public class HistoryType implements UserType {
		private int[] types = { Types.BIGINT, Types.DATE};
		public int[] sqlTypes() {
			return types;
		}
		public Class returnedClass() {
			return History.class;
		}
		public boolean equals(Object a, Object b) throws HibernateException
		{
			return (a == b) ||
			((a != null) &amp;&amp; (b != null) &amp;&amp; (a.equals(b)));
		}
		public int hashCode(Object o) throws HibernateException {
			return o.hashCode();
		}
		public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
				Long initialCapacity = rs.getLong(names[0]);
				// check if the last column read is null
				if (rs.wasNull()) return null;
				Date establishmentDate = rs.getDate(names[1]);
				History history = new History() ;
				history.setInitialCapacity(initialCapacity.longValue());
				history.setEstablishmentDate(establishmentDate);
				return history;
		}
		public void nullSafeSet(PreparedStatement ps, Object value,
			int index) throws HibernateException, SQLException {
			if(value==null){
				ps.setNull(index, Hibernate.LONG.sqlType());
				ps.setNull(index+1, Hibernate.DATE.sqlType());
			}else{
				History history = (History) value;
				long initialCapacity = history.getInitialCapacity();
				Date establishmentDate = history.getEstablishmentDate();
				Hibernate.LONG.nullSafeSet(ps, new Long(initialCapacity),
					index);
				Hibernate.DATE.nullSafeSet(ps, establishmentDate, index + 1);
			}
		}
		public Object deepCopy(Object o) throws HibernateException {
			if (o == null) return null;
			History origHistory = (History) o;
			History newHistory = new History();
			newHistory.setInitialCapacity(origHistory.getInitialCapacity());
			newHistory.setEstablishmentDate(origHistory.
			getEstablishmentDate());
			return newHistory;
		}
		public boolean isMutable() {
			return true;
		}
		public Serializable disassemble(Object value) throws
			HibernateException {
			return (Serializable) value;
		}
		public Object assemble(Serializable cached, Object owner)
			throws HibernateException {
			return cached;
		}
		public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
			return original;
		}
	}

The following table provides a short description for the methods in the UserType interface:

4 5 6 7

In some of the methods shown in the table above, the owner object is passed as an argument to the method. You can use this object if you need the other properties of the value-type instance. For example, you can access a property of the owner if you need it to calculate the value for a value-type property.

Serializing and caching issue
If the value type, in our case History, does not implement the
java.io.Serializable interface, then its respective custom type
is responsible for properly serializing or deserializing the value type.
Otherwise, the value-type instances cannot be cached by the Hibernate
second-level cache service.

To use the defined custom type, you need to edit the mapping file as shown below:

&lt;hibernate-mapping&gt;
		&lt;class name='com.packtpub.springhibernate.ch07.School'
			table='SCHOOL'&gt;
			&lt;id name='id' type='long' column='id'&gt;
				&lt;generator/&gt;
			&lt;/id&gt;
			&lt;b&gt;&lt;property name='history'
				type='com.packtpub.springhibernate.ch07.
					HistoryType'&gt;
				&lt;column='INITIAL_CAPACITY' type='long'/&gt;
				&lt;column='ESTABLISHMENT_DATE' type='date'/&gt;
			&lt;/property&gt;&lt;/b&gt;
			&lt;!-- mapping of other fields --&gt;
		&lt;/class&gt;
	&lt;/hibernate-mapping&gt;

Note that you should specify the columns in order, corresponding to the order of types returned by the getTypes() method and the index of the values the nullSafeGet() and nullSafeSet() handle.

So far, all we have done is implemented a custom type in the simplest form. The implemented custom type only transforms the value-type instances to the database columns and vice versa. A custom type may be more complicated than we have seen so far, and can do much more sophisticated things. The advantage of this implemented custom type is obvious: we can define our own strategy for mapping value types. For instance, a property of the value type can be stored in more than one column, or more than one property can be stored in a single column.

The main shortcoming of this approach is that, we have hidden the value-type properties from Hibernate. Therefore, Hibernate does not know anything about the properties inside the value type, or how to query persistent objects based on their associated value types as problem constraints are involved. Let’s look at CompositeUserType and how it can solve this problem.

CompositeUserType

Another way to define a custom type is to use the CompositeUserType interface. This type is similar to UserType, but with more methods to expose the internals of your value-type class to Hibernate. CompositeUserType is useful when application query expressions include constraints on value-type properties. If you want to query the persistent objects with constraints on their associated value types, map the associated value types with CompositeUserType. The following code shows the CompositeHistoryType implementation for History:

package com.packtpub.springhibernate.ch07;

	import org.hibernate.usertype.CompositeUserType;
	import org.hibernate.type.Type;
	import org.hibernate.HibernateException;
	import org.hibernate.Hibernate;
	import org.hibernate.engine.SessionImplementor;
	import java.sql.ResultSet;
	import java.sql.SQLException;
	import java.sql.PreparedStatement;
	import java.io.Serializable;
	import java.util.Date;

	public class CompositeHistoryType implements CompositeUserType {
		private String[] propertyNames = {'initialCapacity',
					'establishmentDate'};
		private Type[] propertyTypes = {Hibernate.LONG, Hibernate.DATE};
		public String[] getPropertyNames() {
			return propertyNames;
		}
		public Type[] getPropertyTypes() {
			return propertyTypes;
		}
		public Object getPropertyValue(Object component, int property) {
			History history = (History) component;
			switch (property) {
				case 0:
					return new Long(history.getInitialCapacity());
				case 1:
					return history.getEstablishmentDate();
			}
			throw new IllegalArgumentException(property +
					' is an invalid property index for class type ' +
					component.getClass().getName());
		}
		public void setPropertyValue(Object component, int property,
		Object value) {
			History history = (History) component;
			switch (property) {
				case 0:
					history.setInitialCapacity(((Long) value).longValue());
				case 1:
					history.setEstablishmentDate((Date) value);
				default:
					throw new IllegalArgumentException(property +
						' is an invalid property index for class type ' +
						component.getClass().getName());
			}
		}
		public Class returnedClass() {
			return History.class;
		}
		public boolean equals(Object o1, Object o2) throws
		HibernateException {
			if (o1 == o2) return true;
			if (o1 == null || o2 == null) return false;
				return o1.equals(o2);
		}
		public int hashCode(Object o) throws HibernateException {
			return o.hashCode();
		}
		public Object assemble(Serializable cached,
			SessionImplementor session, Object owner)
			throws HibernateException {
				return deepCopy(cached);
		}
		public Object replace(Object original, Object target,
				SessionImplementor sessionImplementor, Object owner)
				throws HibernateException {
					return original;
		}
		public Serializable disassemble(Object value,
			SessionImplementor session)
			throws HibernateException {
				return (Serializable) deepCopy(value);
		}
		public Object nullSafeGet(ResultSet rs, String[] names,
			SessionImplementor session, Object o)
			throws HibernateException, SQLException {
				long initialCapacity = rs.getLong(names[0]);
				java.util.Date establishmentDate = rs.getDate(names[1]);
				return new History(initialCapacity, establishmentDate);
		}
		public void nullSafeSet(PreparedStatement ps,
			Object value, int index, SessionImplementor session)
			throws HibernateException, SQLException {
				if (value == null) {
					ps.setNull(index, Hibernate.LONG.sqlType());
					ps.setNull(index + 1, Hibernate.DATE.sqlType());
				} else {
					History history = (History) value;
					long l = history.getEstablishmentDate().getTime();
					ps.setLong(index, history.getInitialCapacity());
					ps.setDate(index + 1, new java.sql.Date(l));
				}
			}
			public Object deepCopy(Object value) throws HibernateException {
				if (value == null) return null;
				History origHistory = (History) value;
				History newHistory = new History();
				newHistory.setInitialCapacity(origHistory.getInitialCapacity());
				newHistory.setEstablishmentDate(origHistory.
				getEstablishmentDate());
				return newHistory;
			}
			public boolean isMutable() {
				return true;
			}
		}

As you can see, this interface exposes some extra methods not seen in UserType. The following table shows the functionality of these methods:

8 9

Using this custom type is same as using UserType, except that you need to specify the CompositeHistoryType instead of HistoryType as follows:

&lt;property name='history'
		type='com.packtpub.springhibernate.ch07.
		CompositeHistoryType'&gt;
		&lt;column='INITIAL_CAPACITY' type='long'/&gt;
		&lt;column='ESTABLISHMENT_DATE' type='date'/&gt;
	&lt;/property&gt;

As mentioned earlier, this custom type provides an ability to query on properties of the History type. As you will see in Chapter 9, HQL is one approach provided by Hibernate to query the persistent object. For instance, suppose we are interested in schools established before 1980. The following code shows querying these objects with HQL, a Hibernate-specific query language that works with objects:

Calendar c = Calendar.getInstance();
	c.set(Calendar.YEAR, 1980);
	Query q = session.createQuery(
	'select s from School s where s.history.establishmentDate &lt; :edate'
	).setParameter('edate', new Date(c.getTimeInMillis()));

All we have done in this snippet is created a Query object with an HQL expression indicating all School objects with establishment date before 1980. Note that HistoryCompositeType provides the ability to query the School object with criteria applied to History objects. (Don’t worry about this for now since upcoming chapters cover it in detail.)

The only advantage of CompositeUserType over UserType is that CompositeUserType exposes the value-type properties for Hibernate. Therefore, it lets you query persistent instances based on values of their associated value-type instances.

Summary

In this chapter, we discussed Hibernate types, which define the mapping of each Java type to an SQL type. It is the responsibility of the Hibernate dialect and the JDBC driver to convert the Java types to the actual target SQL types. This means a Java type may be transformed to different SQL types when different databases are used.

also read: follow us on @twitter and @facebook

Although Hibernate provides a rich set of data types, called built-in types, some situations require the definition of a new type. One such situation occurs when you want to change Hibernate’s default behavior for mapping a Java type to an SQL type. Another situation is when you want to split up a class property to a set of table columns, or merge a set of properties to a table column.

Built-in types include primitive, string, byte array, time, localization, serializable, and JDBC large types.

Hibernate provides several interfaces for implementation by custom types. The most commonly used interfaces are org.hibernate.usertype.UserType and org.hibernate.usertype.CompositeUserType. The basic extension point is UserType. It allows us to map a value-type, but hides the value-type properties from Hibernate, so it does not provide the application with the ability to query value types. In contrast, CompositeUserType exposes the value-type properties to Hibernate, and allows Hibernate to query the value-types.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*