Java tutorial
package com.usetheindexluke; /** * Demonstrates a Projection to select only selected columns from a join. * The data is accessed via a Map that might, possibly, lead to runtime problems. * Consider using the DTO approach demonstrated in the FewerColumnsJPA sample * or * the byte-code instrumentation demonstrated in FewerColumnsInstrumentedHibernate. */ /* "Use The Index, Luke" by Markus Winand is licensed under a Creative Commons * Attribution-Noncommercial-No Derivative Works 3.0 Unported License. * * http://Use-The-Index-Luke.com/ */ import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; public class FewerColumnsHibernate { public static void main(String[] args) { Session session = new Configuration().configure().buildSessionFactory().openSession(); try { Criteria q = session.createCriteria(Sales.class, "sales"); q.add(Restrictions.gt("saleDate", getSixMonthAgo())); q.createAlias("employee", "employee"); q.setProjection(Projections.projectionList().add(Projections.property("sales.saleDate"), "saleDate") .add(Projections.property("sales.eurValue"), "eurValue") .add(Projections.property("employee.lastName"), "lastName") .add(Projections.property("employee.firstName"), "firstName")); q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); List<Map> result = q.list(); for (Map s : result) { String txt = " Employee: " + s.get("lastName") + " date: " + s.get("saleDate") + " EUR value: " + s.get("eurValue"); // System.out.println(txt); } } finally { session.close(); } } // calculating the boundary date on the client side, avoiding // interoperability problems, especially since HQL doens't provide // INTERVAL calculations // http://opensource.atlassian.com/projects/hibernate/browse/HHH-2434 static Date getSixMonthAgo() { Calendar c = Calendar.getInstance(); c.add(Calendar.MONTH, -6); c.set(Calendar.HOUR, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); return c.getTime(); } }