Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eliminate "unchecked" warnings when using JPA

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?

like image 976
Johan Avatar asked Feb 24 '13 11:02

Johan


People also ask

How can I avoid unchecked cast warnings?

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.

What is suppress warning unchecked?

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.

What is unchecked conversion in Java?

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.


2 Answers

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);
like image 146
Igor Rodriguez Avatar answered Oct 15 '22 11:10

Igor Rodriguez


You can use the Criteria API to avoid this. Check out this question for info on how to use it.

like image 36
Barend Avatar answered Oct 15 '22 11:10

Barend