NimChimpsky
NimChimpsky

Reputation: 47290

Avoid type safety warnings with Hibernate criteria query

final Criteria crit = session.createCriteria(MyClass.class);
final List<MyClass> myClassList = crit.list();

results in this : Type safety: The expression of type List needs unchecked conversion to conform to List

Is their a method to remove the warning, as I get an error using this :

final List<MyClass> myClassList = Collections.checkedList(MyClass.class, crit.list());

Upvotes: 5

Views: 5955

Answers (3)

Ala Varos
Ala Varos

Reputation: 1725

For me, the best way to avoid type safety warning is as Matt Quail says in this post: How to avoid type safety warnings with Hibernate HQL results? , writing a cast-helper, but with Criteria instead of Query, like this:

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

And only you have to call this method:

List<MyClass> myClassList = listAndCast(crit);

Greetings!

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500785

Well, you can use:

@SuppressWarnings("unchecked")

before the declaration...

Note that this will only suppress the warning - it won't do anything to make the code safer. In this case, I'd personally be happy enough about this; I'd trust Hibernate to do the right thing.

Upvotes: 6

Andrew Spencer
Andrew Spencer

Reputation: 16484

In your code

final List<MyClass> myClassList 
    = Collections.checkedList(MyClass.class, crit.list());

you just need to inverse the order of the arguments to checkedList().

Btw you could static import the method to make your code more concise. Also btw, I didn't know about checkedList() - thanks for the heads-up!

Edit: checkedList() doesn't do what you want - as I should have realised if I'd thought about it properly before answering.

checkedList() will check the types of any elements added to the list and fail immediately. As opposed to a normal list which would allow you to put the wrong types in, and fail only upon retrieval. In your case it makes no difference since you're not going to insert items yourself (I guess).

Jon Skeet's answer (@SuppressWarnings("unchecked")) is the right one.

Upvotes: 4

Related Questions