I have entity that has several fields:
public class Some { private Foo foo; private Bar bar; }
I want to have code which is capable to sort by foo and sort by bar depending on the request. I know that there is tool that could be used like this:
Sort sort = Sort.by(Sort.Direction.DESC, "foo"); Pageable pageable = PageRequest.of(page, limit, sort);
But it seems like this approach is not perfect because field names are hardcoded and in the case that some field name is changed and developer forgot to update this sorting code everything will look okay during compilation / startup stage, but will fail during runtime.
Is that possible to have alternative solution without hardcoding and duplicating same method several times just to change jpql query ?
Advertisement
Answer
If you don’t want to use a String
for the names, you can use the JPA Metamodel. This metamodel you can also use the create queries with the criteria API.
Here is a nice blog post which explains how to generate and use the JPA Criteria Metamodel. But in short it comes down to adding a Maven plugin (or Gradle if you use that) to your compiler. During compilation it will now generate the metamodel.
With your sample class(es)
public class Some { private Foo foo; private Bar bar; }
It will generate a Some_
class which you can then use to get the name of the properties. Some_.FOO
will link to the foo
attribute. Now if you rename foo
to bar
, compilation will fail as Some_FOO
isn’t available anymore.