Friday, September 28, 2012

Hibernate Criteria Snippets



The very basic
session.createCriteria(Car.class);

session.createCriteria(Car.class)
.add(Restrictions.eq(“engine.code”, code))
.uniqueResult();

Collections: isEmpty(), size()
session.createCriteria(Student.class)
         .add(Restrictions.isEmpty(“courses”, 2));

Ignore case:
session.createCriteria(Student.class)
         .add(Restrictions.eq(“name”, name).ignoreCase());

session.createCriteria(Student.class)
         .add(Restrictions.ilike(“name”, name));


Wildcard:
session.createCriteria(Student.class)
         .add(Restrictions.like(“name”, “test%”));

session.createCriteria(Student.class)
         .add(Restrictions.like(“name”, “test”, MatchMode.START));


Logical Operations:
session.createCriteria(Student.class)
         .add(Restrictions.or(
                  Restrictions.and(
                           Restrictions.eq(“firstname”, fn), Restrictions.eq(“lastname”, ln)
                  ),
                  Restrictions.in(“subject”, subjects)
         ));

Projections & Transformers:
session.createCriteria(Student.class)
         .setProjection(Projections.projectionList()
                  .add(Projections.property(“name”).as(“studentName”))
                  .add(Projections.property(“section”).as(“section”)))
         .setResultTransformer(Transformers.aliasToBean(StudentDTO.class));


Aggregation:
session.createCriteria(Order.class)
         .setProjection(Projections.projectionList()
                  .add(Property.forName(“id”).group())
                  .add(Property.forName(“style”).count())
                  .add(Property.forName(“amount”).avg()));

SqlProjections:
String sql = “(select avg(o.amount) from Orders o where o.id= order_id) as avgAmount”;
session.createCriteria(Receipt.class)
         .createAlias(“orders”, “o”)
         .setProjection(Projections.projectionList()
                  .add(Projections.groupProperty(“o.id”))
                  .add(Projections.sqlProjection(
                           sql,
new String[]{“avgAmount”},
new Type[]{new BigDecimalType()})));


Conjunction & Disjunction:
Criteria criteria = session.createCriteria(Order.class);
Conjunction contact1Filter = Restrictions.conjunction();
      contact1Filter.add(Restrictions.eq("c1_firstname", c1fn));
      contact1Filter.add(Restrictions.eq("c1_lastname", c1ln));


Conjunction contact2Filter = Restrictions.conjunction();
      contact2Filter.add(Restrictions.eq("c2_firstname", c2fn));
      contact2Filter.add(Restrictions.eq("c2_lastname", c2ln));

Disjunction contact1Or2Filter = Restrictions.disjunction();
      contact1Or2Filter.add(contact1Filter);
      contact1Or2Filter.add(contact2Filter);

criteria.add(contact1Or2Filter);

... results in >>
 FROM Order WHERE 
  (c1_firstname AND c1_lastname)  -- conjunction 
     OR                           -- disjunction
  (c2_firstname AND c2_lastname)  -- conjunction


No comments: