如何使用 Hibernate HQL 结果避免类型安全警告?

例如,我有这样的疑问:

Query q = sess.createQuery("from Cat cat");
List cats = q.list();

如果我尝试这样做,它会显示以下警告

Type safety: The expression of type List needs unchecked conversion to conform to List<Cat>




List<Cat> cats = q.list();

有办法避免吗?

72447 次浏览

In our code we annotate the calling methods with:

@SuppressWarnings("unchecked")

I know it seems like a hack, but a co-developer checked recently and found that was all we could do.

No, but you can isolate it into specific query methods and suppress the warnings with a @SuppressWarnings("unchecked") annotation.

If you don't want to use @SuppressWarnings("unchecked") you can do the following.

   Query q = sess.createQuery("from Cat cat");
List<?> results =(List<?>) q.list();
List<Cat> cats = new ArrayList<Cat>();
for(Object result:results) {
Cat cat = (Cat) result;
cats.add(cat);
}

FYI - I created a util method that does this for me so it doesn't litter my code and I don't have to use @SupressWarning.

We use @SuppressWarnings("unchecked") as well, but we most often try to use it only on the declaration of the variable, not on the method as a whole:

public List<Cat> findAll() {
Query q = sess.createQuery("from Cat cat");
@SuppressWarnings("unchecked")
List<Cat> cats = q.list();
return cats;
}

Using @SuppressWarnings everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call q.list().

There are two other techniques I'd suggest:

Write a cast-helper

Simply refactor all your @SuppressWarnings into one place:

List<Cat> cats = MyHibernateUtils.listAndCast(q);


...


public static <T> List<T> listAndCast(Query q) {
@SuppressWarnings("unchecked")
List list = q.list();
return list;
}

Prevent Eclipse from generating warnings for unavoidable problems

In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox Ignore unavoidable generic type problems due to raw APIs

This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable.

Some comments:

  • I chose to pass in the Query instead of the result of q.list() because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any List in general.
  • You could add similar methods for .iterate() etc.

We had same problem. But it wasn't a big deal for us because we had to solve other more major issues with Hibernate Query and Session.

Specifically:

  1. control when a transaction could be committed. (we wanted to count how many times a tx was "started" and only commit when the tx was "ended" the same number of times it was started. Useful for code that doesn't know if it needs to start a transaction. Now any code that needs a tx just "starts" one and ends it when done.)
  2. Performance metrics gathering.
  3. Delaying starting the transaction until it is known that something will actually be done.
  4. More gentle behavior for query.uniqueResult()

So for us, we have:

  1. Create an interface (AmplafiQuery) that extends Query
  2. Create a class (AmplafiQueryImpl) that extends AmplafiQuery and wraps a org.hibernate.Query
  3. Create a Txmanager that returns a Tx.
  4. Tx has the various createQuery methods and returns AmplafiQueryImpl

And lastly,

AmplafiQuery has a "asList()" that is a generic enabled version of Query.list() AmplafiQuery has a "unique()" that is a generic enabled version of Query.uniqueResult() ( and just logs an issue rather than throwing an exception)

This is a lot of work for just avoiding @SuppressWarnings. However, like I said (and listed) there are lots of other better! reasons to do the wrapping work.

It's not an oversight or a mistake. The warning reflects a real underlying problem - there is no way that the java compiler can really be sure that the hibernate class is going to do it's job properly and that the list it returns will only contain Cats. Any of the suggestions here is fine.

I know this is older but 2 points to note as of today in Matt Quails Answer.

Point 1

This

List<Cat> cats = Collections.checkedList(Cat.class, q.list());

Should be this

List<Cat> cats = Collections.checkedList(q.list(), Cat.class);

Point 2

From this

List list = q.list();

to this

List<T> list = q.list();

would reduce other warnings obviously in original reply tag markers were stripped by the browser.

Apparently, the Query.list() method in the Hibernate API is not type safe "by design", and there are no plans to change it.

I believe the simplest solution to avoid compiler warnings is indeed to add @SuppressWarnings("unchecked"). This annotation can be placed at the method level or, if inside a method, right before a variable declaration.

In case you have a method that encapsulates Query.list() and returns List (or Collection), you also get a warning. But this one is suppressed using @SuppressWarnings("rawtypes").

The listAndCast(Query) method proposed by Matt Quail is less flexible than Query.list(). While I can do:

Query q = sess.createQuery("from Cat cat");
ArrayList cats = q.list();

If I try the code below:

Query q = sess.createQuery("from Cat cat");
ArrayList<Cat> cats = MyHibernateUtils.listAndCast(q);

I'll get a compile error: Type mismatch: cannot convert from List to ArrayList

Try this:

Query q = sess.createQuery("from Cat cat");
List<?> results = q.list();
for (Object obj : results) {
Cat cat = (Cat) obj;
}

It is been a long time since the question was asked but I hope my answer might be helpful to someone like me.

If you take a look at javax.persistence api docs, you will see that some new methods have been added there since Java Persistence 2.0. One of them is createQuery(String, Class<T>) which returns TypedQuery<T>. You can use TypedQuery just as you did it with Query with that small difference that all operations are type safe now.

So, just change your code to smth like this:

Query q = sess.createQuery("from Cat cat", Cat.class);
List<Cat> cats = q.list();

And you are all set.

A good solution to avoid type safety warnings with hibernate query is to use a tool like TorpedoQuery to help you to build type safe hql.

Cat cat = from(Cat.class);
org.torpedoquery.jpa.Query<Entity> select = select(cat);
List<Cat> cats = select.list(entityManager);

Try to use TypedQuery instead of Query. For example instead of this:-

Query q = sess.createQuery("from Cat cat", Cat.class);
List<Cat> cats = q.list();

Use this:-

TypedQuery<Cat> q1 = sess.createQuery("from Cat cat", Cat.class);
List<Cat> cats = q1.list();

Newer versions of Hibernate now support a type safe Query<T> object so you no longer have to use @SuppressWarnings or implement some hack to make the compiler warnings go away. In the Session API, Session.createQuery will now return a type safe Query<T> object. You can use it this way:

Query<Cat> query = session.createQuery("FROM Cat", Cat.class);
List<Cat> cats = query.list();

You can also use it when the query result won't return a Cat:

public Integer count() {
Query<Integer> query = sessionFactory.getCurrentSession().createQuery("SELECT COUNT(id) FROM Cat", Integer.class);
return query.getSingleResult();
}

Or when doing a partial select:

public List<Object[]> String getName() {
Query<Object[]> query = sessionFactory.getCurrentSession().createQuery("SELECT id, name FROM Cat", Object[].class);
return query.list();
}
TypedQuery<EntityName> createQuery = entityManager.createQuery("from EntityName", EntityName.class);
List<EntityName> resultList = createQuery.getResultList();