persistence icon indicating copy to clipboard operation
persistence copied to clipboard

Introduce specialized expression types for easier JPA Criteria querying

Open beikov opened this issue 2 years ago • 2 comments

I don't know how feasible this is, but this idea just came to mind and I wanted to share it here.

What if we introduced special Attribute, Expression and Path types for certain known types to make it easier to construct predicates and/or functions. I propose the following additions:

  • NumberAttribute, NumberExpression and NumberPath when the type extends Number
  • StringAttribute, StringExpression and StringPath when the type extends String
  • TemporalAttribute, TemporalExpression and TemporalPath when the type extends Temporal
  • ComparableAttribute, ComparableExpression and ComparablePath when the type extends Comparable

Then we add some overloads to Path:

NumberPath<Y> get(NumberAttribute<? super X, Y> attribute);
...

And all of a sudden we could write nicer queries that don't involve calling methods on the CriteriaBuilder e.g.:

cq.where( root.get(MyType_.price).plus(1).gt(10) )

instead of

cq.where( cb.gt( cb.sum( root.get(MyType_.price), 1), 10) )

Of course this is just a simple example, but I think that the major criticism against the JPA Criteria API is that it is hard to write and read, which I think is mostly due to the need of involving the CriteriaBuilder everywhere.

I know that there is a small "type explosion" here i.e. 3 classes for every type we want to add decent support for, but I think it's worth it and that the number of supported types will stay in the single digit realm :)

beikov avatar Aug 31 '23 16:08 beikov

That's a good idea @beikov.

How about prototyping your proposal as a pull req?

gavinking avatar Aug 31 '23 17:08 gavinking

Hello,

i like the idea. :)

Cheers

AleksNo avatar Aug 31 '23 19:08 AleksNo