Search code examples
javahibernatejakarta-eehibernate-criteria

How to avoid string members in hibernate?


Is it possible to avoid using string literials in Hibernate, such as in criteria restrictions and projections:

Criteria criteria = session.createCriteria(Employee.class)
                   .add(Restrictions.eq("name", "john doe"));

or

Projection p1 = Projection.property("name");

For example, in the code snippets above, replacing "name" with something.name , where something contains all the members of the Employee class.

It would make it less error prone, e.g. typo in the string.

EDIT: Updating question to be more general and not specific to just Criteria.


Solution

  • You can create a Employee Constants class:

    public class EmployeeConstants {
            public static final String firstName= "firstname";
            public static final String lastName= "lastname";
            ....
    }
    

    And call the field as :

    Criteria criteria = session.createCriteria(Employee.class)
                       .add(Restrictions.eq(EmployeeConstants.firstName, "john doe"));
    

    In fact EmployeeConstants.firstNamereturns firstname which must be the field name of the Employee Entity.