Domanda

I want to write a Criteria query, that will do something like this:

SELECT a, b FROM t WHERE a + b < 10

Is this possible using Criteria API?

È stato utile?

Soluzione

Yes . You can use Restrictions.sqlRestriction() to define the where clause using native SQL.

   Integer condition = 10;
   List<Object[]> results = (List<Object[]>)session.createCriteria(someTable.class)
            .add(Restrictions.sqlRestriction("a + b < ?" , condition , StandardBasicTypes.INTEGER ))
            .setProjection(Projections.projectionList()
                   .add(Projections.property("a"))
                   .add(Projections.property("b"))
             )
            .list();

Important points :

  • In the return result , the value of column a is stored in Object[0] while b is stored in Object [1] .

  • The input parameters in the Restrictions.sqlRestriction() are the actual column name in the database while the input parameters in the Projections.property() are the java property name of the mapped Entity.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top