Over a million developers have joined DZone.

Hibernate Projections Using Spring

DZone's Guide to

Hibernate Projections Using Spring

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Last week I wanted to learn about Hibernate projections, and while the online documentation was certainly helpful, I was wishing for a sample project that included some data to play with.  I couldn't find one, so I went ahead worked one up myself.

First I used JPA annotations to define a model class:

@Table(name = "DOCUMENT")
public class Document {
@SequenceGenerator(name = "DOCUMENT_SEQ", sequenceName = "DOCUMENT_SEQ",allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DOCUMENT_SEQ")
@Column(name = "DOCUMENT_ID")
private Long id;

@Column(name = "BUS_SEG")
private String busSeg;

@Column(name = "NOTE")
private String note;

@Column(name = "RCVD_DATE")
private Date receivedDate;

For reference, here is a corresponding Oracle table definition:

CREATE TABLE document (
document_id number(10) PRIMARY KEY,
bus_seg varchar2(256),
note varchar2(256),
rcvd_date date

Then I defined a simple DAO interface defining CRUD methods and implemented it by extending Spring's HibernateDAOSupport class:

public class HibernateDocumentDAO extends HibernateDaoSupport implements
DocumentDAO {

public Serializable create(Document document) {
return getHibernateTemplate().save(document);

Now for the projections bit. Once you have a few Documents persisted in your database you may want to see a summary count of the persisted Documents, as distributed over business segments (e.g., 'Federal', 'State', 'Commercial').  For good measure, you want to compute the minimum (oldest) received date of the Documents in each group, in order to locate Documents that have been waiting longest for human attention:

SELECT count(*), bus_seg, MIN(rcvd_date) 
FROM document
GROUP BY bus_seg;

You can write queries like that using Hibernate projections.  But how about a projection service that exposes the projection concept to the client side?  The service could be written in terms of a technology-neutral QuerySpecification for which a Hibernate implementation is provided:

		QuerySpecification spec = new QuerySpecification();
spec.addProjection(new QuerySpecification.Projection(DocumentDAO.BUS_SEG, QuerySpecification.Function.GROUP_BY));
spec.addProjection(new QuerySpecification.Projection(DocumentDAO.RCVD_DATE, QuerySpecification.Function.MIN));
List<Object[]> results = (List<Object[]>) documentService.query(spec);

Each member of the results collection represents a row returned from the Hibernate projection.  The first element of each row is an integer (the count), the second element is a String (the businesss segment), and the third element is a java.sql.Timestamp (the minimum received date)

I've deliberately left in a smelly bit of code in the QuerySpecification example above.  The client of the documentService is making use of String constants defined in the DAO interface.  At one level, this is because I was too lazy to re-define the property names in the service layer.  At another level, I think it is a sign that I am bending the object-relational model a bit here by exposing projections at the service layer.  Ideally, clients of the document service shouldn't know if Hibernate or even SQL is being used for persistence.  However, I hope you forgive the liberty taken if you see the power of using projections to summarize your data.

I have the complete example in the form of a maven project that I am willing to share with anyone interested.




Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}