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.
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.firstName
returns firstname
which must be the field name of the Employee
Entity.