Search code examples
javasqlhibernatehibernate-criteria

Hibernate Criteria API and field selectors?


In Hibernate, I like the Criteria API, but it doesn't seem to allow you to specify certain columns for a specific entity class. For instance, given the following table:

log_entries
    id : PRIMARY KEY AUTO INCREMENT INTEGER
    timestamp : datetime
    log_level : varchar(25)
    originator : varchar(200)
    message : text

How could I write the following SQL query using the Criteria API:

SELECT
    timestamp,
    log_level
FROM
    log_entries
WHERE
    timestamp > '2013-06-05 00:00:00'
    AND
    originator <> 'com.me.myapp.SomeObject'

Solution

  • you need to use ProjectionList to get specific columns records, follow the steps

    Criteria criteria  = session.createCriteria(LogEntries.class);
    
    //select columns
    ProjectionList columns = Projections.projectionList();
    columns.add(Projections.property("timestamp"));
    columns.add(Projections.property("log_level"));
    criteria.setProjection(columns);
    
    //conditions
    Criterion timestamp = Restrictions.gt("timestamp", "2013-06-05 00:00:00");
    Criterion originator = Restrictions.not(Restrictions.eq("originator", "com.me.myapp.SomeObject"));
    LogicalExpression condition = Restrictions.and(timestamp, originator);
    
    criteria.add(condition);
    List results = criteria.list();