The new Java EE5 Persistence provides some really cool functionality. It was designed with backwards compatibility in mind. This has resulted in some interesting issues. For example if you perform a Query which returns more than one object, the objects are returned as a List. The List is a very generic Object List. Generally we know that if we perform a query that it should return specific types back to us. For example we expect it to return a collection of the entity itself. If we accept the default which is to return a List, the compiler will report an unchecked warning. If you use the -Xlint:unchecked option, it will point out that we are getting a generic Object List and it can not verify the type of the Object.
The Solution... is simple...When you get the List back cast it into a specific type. For example:
Query q = em.createQuery("SELECT OBJECT(p) FROM PuzzleBox p");
List puzzles = q.getResultList();
A rather elegent solution... alternatively you can have a more complex version such as
ArrayList puzzles = new ArrayList(q.getResultList);
This works because an ArrayList can accept a Collection as noted in the Javadocs:
ArrayList(Collection<? extends E> c)
The last and most inelegent solution is to annotate the methods which use the generic List of Objects to suppress the complier warnings with a @SuppressWarnings("unchecked") annotation.
0 comments :
Post a Comment