Issue with generic in Hibernate Template

I use Hibernate Template and have this code:

public List<Book> findBooksByName(String name) {
    return getHibernateTemplate().find("FROM Book WHERE name = ?", name);
}

I thought it looked good. But when I ran this code, I got an error:

[ERROR] incompatible types
[ERROR] required: java.util.List<com.model.Book>
[ERROR] found:    java.util.List<capture#1 of ?>

How can I fix it and get what I need? Thank you in advance!

Upvotes: 3

Views: 256

Answers (1)

Tamas Rev
Tamas Rev

Reputation: 7166

As far as I can tell, you are extending a HibernateDaoSupport as explained in this example. getHibernateTemplate() will return a HibernateTemplate without any type specification. Which is all right because HibernateTemplate doesn't have type parameters.

So this find(...) method will return a List of Objects. The actual Hibernate code might return List of HibernateProxy instances. This HibernateProxy is an automatically generated subclass of your domain class, Book in this case.

So all you can do is to cast the result to the right kind of list:

public List<? extends Book> findBooksByName(String name) {
    return (List<? extends Book>) getHibernateTemplate().find("FROM Book WHERE name = ?", name);
}

This will make your List effectively read-only. This is the price that we pay for ORM convenience.

Upvotes: 1

Related Questions