Tutorial Chapter 2 – Easier Development and Maintenance
Tired of wiring in an id
, and timestamp
field into all of your Hibernate objects? There’s an easy way to solve this pain once and for all of your classes. Avoid code-repetition: today’s article focuses on using Hibernate Annotations to map common fields into one mapped superclass.
If you have not done so already, and need to get a bare bones hibernate application up and running, this guide
should get you up and running in a few minutes.
You’re using Hibernate, or at least getting your feet wet at this point, so let’s assume that you’ve started to notice a pattern. You need in all of your objects:
- an id column
- a version column
- perhaps a timestamp column
Lets say that you are also aware of the hashcode() and equals() issues
that come with using objects in collections, so you want to define some basic functionality to handle that situation as well.
It would be pretty nice if we could do all this in one place, keeping updates quick and painless. Well, using the EJB-3/Hibernate @MappedSuperclass
annotation, we can. Mapped superclass tells Hibernate that you want all mappings defined in the base class to apply and be included in all classes which extend from it.
Let’s take a look at an example base-class that will meet our above needs.
- Copy the following code examples into your HIbernate Annotations enabled project
public abstract class PersistentObject implements Serializable
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id = null;
@Column(name = "version")
private int version = 0;
@Column(name = "last_update")
private Date lastUpdate;
protected void copy(final PersistentObject source)
this.id = source.id;
this.version = source.version;
this.lastUpdate = source.lastUpdate;
public boolean equals(final Object obj)
if (this == obj)
if (obj == null)
if (!(obj instanceof PersistentObject))
final PersistentObject other = (PersistentObject) obj;
if (this.id != null && other.id != null)
if (this.id != other.id)
protected static boolean getBooleanValue(final Boolean value)
public Long getId()
private void setId(final Long id)
this.id = id;
public int getVersion()
private void setVersion(final int version)
this.version = version;
public Date getLastUpdate()
public void setLastUpdate(final Date lastUpdate)
this.lastUpdate = lastUpdate;
Extending the Base Class:
Using the MockObject class from Chapter 1, now extend PersistentObject. We can remove the fields that are now mapped in PersistentObject and add new fields to fit our business needs. Notice that MockObject does not define fields or methods for id
, or timestamp
; this behavior is now contained within our mapped superclass.
From now on, all you need to do to incorporate this behavior into new classes is to extend PersistentObject.
@Table(name = "mock_objects")
public class MockObject extends PersistentObject
private static final long serialVersionUID = -3621010469526215357L;
private String textField;
private long numberField;
public String getTextField()
public void setTextField(String textField)
this.textField = textField;
public long getNumberField()
public void setNumberField(long numberField)
this.numberField = numberField;
To prove it, we’ll re-run our demo application from the quick-start guide. Notice that the results are the same. I’ve added a little logic to show that our new columns work as well.
Our driver class does the following things:
For referenced HibernateUtil,java, please see Chapter 1.
- Get a handle to Hibernate Session
- Create and persist two new MockObjects
- Assign values into the textField of each object
- Print out the generated IDs and set fields
public class HibernateDemo
public static void main(String args)
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction transaction = session.beginTransaction();
MockObject object0 = new MockObject();
object0.setTextField("I am object 0");
MockObject object1 = new MockObject();
object1.setTextField("I am object 1");
System.out.println("Generated ID is: " + object0.getId());
System.out.println("Generated Version is: " + object0.getVersion());
System.out.println("Generated ID is: " + object1.getId());
System.out.println("Generated Version is: " + object1.getVersion());
Which results in the following output:
I am object 0
Generated ID is: 1
Generated Version is: 0
I am object 1
Generated ID is: 2
Generated Version is: 0
Considering the Forces:
It may be worth mentioning that using a base class for all of your objects can be a blessing and a curse. If you begin to reference objects using the more generic PersistentObject type, it is possible that you could find yourself constrained to the behavior of this one class. When this happens, consider defining PersistentObject as an Interface
and then implement that interface with any number of @MappedSuperclass
There are benefits to referencing objects by their generic type, as well. One example, which we’ll take a look at this when we dive into the Dao
pattern, makes it very easy to perform a wide array of operations on your Hibernate objects.
Congratulations. You should now have a mapped superclass to contain your common functionality.
- Hibernate’s Standard Tutorial
- Hibernate Annotations Reference
This article is part of a series: Guide to Hibernate Annotations
About the author:
Lincoln Baxter, III is the Chief Editor of Red Hat Developers, and has worked extensively on JBoss open-source projects; most notably as creator & project lead of JBoss Forge, author of Errai UI, and Project Lead of JBoss Windup. This content represents his personal opinions, not those of his employer.
He is a founder of OCPsoft, the author of PrettyFaces and Rewrite, the leading URL-rewriting extensions for Servlet, Java EE, and Java web frameworks; he is also the author of PrettyTime, social-style date and timestamp formatting for Java. When he is not swimming, running, or playing competitive Magic: The Gathering, Lincoln is focused on promoting open-source software and making technology more accessible for everyone.