I discovered JPA 2.0 Criteria API today and want to learn it. Just went through some examples and try to do a hands on. I have a table fruit with columns:
- id,
- name,
- color,
- size,
- taste.
The regular stuff:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("fruitManager");
EntityManager em = emf.createEntityManager();
//get the criteria builder
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Fruit> c = cb.createQuery(Fruit.class);
How will the following query get built using criteria:
select id, name, color where name like 'XY%' and color='orange'
I.e. how to:
- fetch only some columns,
- include wild card search,
- include AND, OR where conditions.
- Also, its always better to get count of the result first before fetching the actual data. How can I fetch the result count first?
Also Is there any place where I can get more examples on 'Criteria' with several different kinds of SQL queries?
Basic tutorial of criteria API can be found at http://download.oracle.com/javaee/6/tutorial/doc/gjivm.html.
Examples can be found at http://www.altuure.com/2010/09/23/jpa-criteria-api-by-samples-part-i/ , also check part 2.
First, you operate to Entities, not to tables, so I will assume following mapping for Fruit:
When result consists of separate columns, type argument to query is Object[].class (result will be List of Object[]). Other possibility is to use Tuple. You can build query you described with following. Just for being clear about type of argument for the sake of example, intermediate variables are created for Predicates and ParameterExpressions. You can also inline those to the query creation.
You can also build same query by inlining everything:
Or use Tuple as result type:
If you go for canonical metamodel, then you need following class in same package with your fruit. It is up to you do you write it by yourself or generate with some tool (for example with org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor). First time it makes sense to write it by yourself:
Then you can go for strongly typed arguments and replace query in former tuple example with following: