jakartaee / persistence

https://jakartaee.github.io/persistence/
Other
203 stars 59 forks source link

Introduce specialized expression types for easier JPA Criteria querying #519

Open beikov opened 1 year ago

beikov commented 1 year ago

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:

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 :)

gavinking commented 1 year ago

That's a good idea @beikov.

How about prototyping your proposal as a pull req?

AleksNo commented 1 year ago

Hello,

i like the idea. :)

Cheers