I do a lot of querying with javax.persistence. And Java forces me to either suffer warnings or @Suppress them, neither of which feels right.
@SuppressWarnings("unchecked")
@Override
public List<Area> getArea(Province province) {
Query qry = em.createQuery("Select c from Area c where c.province = ?1");
qry.setParameter(1, province);
return qry.getResultList();
}
How do I eliminate the warning in the above code?
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
In other words, it basically, tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
The warning message “unchecked conversion” implies that we should check the conversion before the assignment. To check the type conversion, we can go through the raw type collection and cast every element to our parameterized type.
If you're using JPA annotations, use TypedQuery
instead of Query
:
TypedQuery<Area> qry = em.createQuery(
"Select c from Area c where c.province = ?1", Area.class);
You can use the Criteria API to avoid this. Check out this question for info on how to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With