jakartaee / persistence

https://jakartaee.github.io/persistence/
Other
196 stars 58 forks source link

Add generic to Query instance #375

Closed Quix0r closed 1 year ago

Quix0r commented 2 years ago

This is a copied issue from https://bugs.eclipse.org/bugs/show_bug.cgi?id=522384 I had reported: I hope I'm at the right spot.

The javax.persistence.Query should be enhanced with a generic to avoid dangerous casts. Some methods like getSingleResult() and getResultList() or even more will benefit from it, requiring no casting and no pre-check if the cast may work.

Some current Java code: (I assume here, the field "em" is already properly injected with the entity manager)

final Query query = this.em.createNamedQuery("SearchFooById");

query.setParameter("fooId", fooId);

final Object result = query.getSingleRest();

if (!(result instanceof Foo)) {
    throw new ClassCastException("result is not instance of Foo");
}

final Foo foo = (Foo) result;

New, proposed way:

final Query<Foo> query = this.em.createNamedQuery("SearchFooById");

query.setParameter("fooId", fooId);

final Foo foo = query.getSingleResult();
gavinking commented 1 year ago

I don't understand this issue. TypedQuery is the genericized version of Query. If we added a type parameter to Query, then we wouldn't need TypedQuery anymore.

gavinking commented 1 year ago

EntityManager has had this method for a very long time:

<T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);

I believe this is all that's needed.

I'm going to close this; if @Quix0r speaks up to explain how this isn't a solution, we can always reopen this.

Quix0r commented 1 year ago

Okay, so I just have to replace Query with TypeQuery<User> and then I can remove the @SuppressWarnings from the method?

gavinking commented 1 year ago

Correct.

Quix0r commented 1 year ago

Then this ticket needs being marked as invalid and maybe locked?