Showing posts with label generics. Show all posts
Showing posts with label generics. Show all posts

Wednesday, April 11, 2012

JPA: Dynamic search builder, the power of annotation, reflection and generics.

JPA (Java persistence API) is a powerful tool for domain objects mapping, and object oriented view perspective of database.

Always I used to use JPA in my projects, but JPA2 introduces extra feature that facilitate the generic way of persisting, merging, deleting and searching. Also introduces dynamic criteria API, which I was looking for.

But with time I have to change the dynamic query or do it myself or else to create new dynamic one which the panic way.

I need a component to search dynamically based on passed object attributes value, and not changed by the time.

For example if I have Bank that has (id, name, address, and state object), and I have created a bank object with name and address has values construct the JPQL SELECT statement (SELECT b FROM Bank b where b.name = :name AND b.address = :address) and search by it and so on.

I have developed a component to implement the above case called DynamicQueryBuilder with advanced techniques, and configurations.

In this article I will describe how I built this component with support of annotation, reflection and generics. In the code snippets you will find a brief description about each line of code and methods, the annotation developed to support the component and I will describe also the overall functionality of the component and how to call it to work dynamically…

Monday, March 19, 2012

JPA: Query, incompatible types compilation error

I have faced a problem while I am writing a generic JPA query like the following:

Compile it and you will get the following error in Jdeveloper 11.1.2.1.0
Error(200,37): incompatible types.

It works for Query.getResultList(), but it doesn't work for Query.getSingleResult().

A work around solves the problem which is, cast to T as (T) query.getSingleResult();

After investigation the perfect solution is to rewrite the following statement:

To be:

Use TypedQuery instead of Query and JDeveloper will remove all "Unchecked conversions from Object to T unsound but tolerated" warnings.

Note: that TypedQuery introduced in JPA 2.