Skip to main content

Improving support for generics in the Java Persistence API

Posted by inder on January 3, 2007 at 11:42 AM PST

The Java Persistence API comes in handy for creating object relational mapping. I recently came across a warnings that the compiler generates on some code that uses these APIs in our Web 2.0 Pet Store project. Upon a closer look, I concluded that the warning was bogus and came up with a suggestion for the Persistence API expert group to better support generics. Here is the warning in question:

D:\ws\petstore\ws\apps\petstore\src\java\com\sun\javaee\blueprints\petstore\model\ warning: [unchecked] unchecked conversion

found   : java.util.List

required: java.util.List<com.sun.javaee.blueprints.petstore.model.Category>

Here is the code that causes this warning to be generated:

Query query = em.createQuery("SELECT c FROM Category c");

List<Category> categories = query.getResultList();

Essentially, the compiler is complaining that query.getResultList() returns just List whereas we are expecting it to be List<Categories>. This warning is unfortunate because we know that the query results are going to be list of Category objects, and we would like to express it somehow. Ideally, javax.persistence.Query should allow us to express this by providing an additional method:

List<T> getResultList(Class<T> c);

This will enable us to write the following code:

List<Category> categories = query.getResultList(Category.class);

and the warning will get eliminated and we will have improved type-safety.

I hope the Java Persistence expert group will look at this issue and add a generic version to ensure better type-safety. I hope they will look at other API methods as well to see if better support for generics can be added.

What is your opinion on this matter? Do you have other suggestions for improving the Java Persistence API? Share your thoughts as comments to this blog. Thanks for reading.

Related Topics >>