When or why do I use Property.forName ()?

What's the difference between:

List cats = session.createCriteria(Cat.class) .add( Restrictions.like("name", "F%") .list(); 

and

 List cats = session.createCriteria(Cat.class) .add( Property.forName("name").like("F%") ) .list(); 

Or, for that matter, the difference between:

 Criteria cr = session.createCriteria(User.class) .setProjection(Projections.projectionList() .add(Property.forName("id").as("id")) .add(Property.forName("name").as("name")) 

and

 Criteria cr = session.createCriteria(User.class) .setProjection(Projections.projectionList() .add(Projections.property("id"), "id") .add(Projections.property("Name"), "Name")) 
+7
hibernate hibernate-criteria
source share
1 answer

Property.forName("propName") always returns you the corresponding instance of Property .

Having said that, it means that there is no difference between the first two code snippets posted in your question. You must use Property.forName("propName") when you need to use this property several times in Criteria or Request . This is equivalent to using a direct number. ( eg 11 ) or using the variable assigned by no. ( eg int x = 11 ) and use a variable every time you need to use no.

See more details.

Now, if I talk about the 2nd question (3rd and 4th code fragments), the work of both is the same. The only difference is the use of the API.

In the 3rd code snippet, you get an instance of Property by calling its as() method, which is used to create an alias for this particular property and returns an instance of SimpleProjection (subclass of Projection) .

In the fourth code snippet, you get an instance of PropertyProjection (subclass of Projection) by executing Projections.property("Name") .

So, in both cases, you get an instance of Projection that you add to the ProjectionsList . ProjectionList now has 2 overloaded methods called add() . In the third code snippet, you call add() , which takes only an instance of Projection as an argument. In the fourth code snippet, you call another version of add() , which takes an instance of Projection as the first argument and alias for the property of Projection as the second argument. Thus, in the end, the work of both is the same.

+6
source share

All Articles