JPA 2 and Netbeans Guide – Part 3 – Querying

March 13th, 2010  | Tags: , , , , , ,

This is the third part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
Part three is gonna use the same example than Part 1, but now we’re going to use the query mechanism to retrieve values from database.

Requirement

  • Understand JPA concepts – If you have no idea what JPA is, please google it first
  • Netbeans 6.8 and glassfish v3 installed
  • MySQL database installed – If you have another one, make sure you have the JDBC driver
  • Read Part 1 and have the database and POJO already created.

Querying strategy

The most common way to retrieve values from relational databases is through an SQL Select Query, probably you have already wrote a lot of them. JPA has this ability and much more.
Since version one, JPA allows you to retrieve values from native query, JPA-QL and NamedQuery, which uses JPA-QL. In version 2, JPA brings us another great API, Criteria API.

Native Query

Let’s get started with the most popular, but less used in JPA: Native Query.
This kind of query must be used only when you need a specific command/resource from the database. Creating many specific queries, your application is going to be dependent from the database, it can be a disadvantage.
To use the native query, simply use the createNativeQuery method from EntityManager. Let’s see the same example from part 1, but using the Native Query.

    public static void main(String[] args) {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("JPAExample01PU");
        EntityManager em = emFactory.createEntityManager();
        List<Products> listProducts = em.createNativeQuery("select * from products", Products.class).getResultList();
        for (Products product : listProducts) {
            System.out.println("Product: " + product.getDescription());
            System.out.println("Price: " + product.getPrice());
            System.out.println("---------------------------------------");
        }
    }

The change happened on line 4. We have added the createNativeQuery method. The first parameter is the Select Query itself and the second one is the class where the result must be mapped.

JPA-QL

This is the query language for JPA. It is similar than SQL, but it uses object approach. There is a method called createQuery that returns a list of objects. See the example

List<Products> listProducts = em.createQuery("select p from Products p").getResultList();

The example above seems similar than the NativeQuery, but the biggest difference appear when you use JOIN. Supposing our Products table has a relationship with another table called Categories. We could create a JPA Query like this:

List<Products> listProducts = em.createQuery("select p from Products p inner join p.categories").getResultList();

We’re going to talk about relationship in Part 5.

NamedQuery

NamedQuery is the kind of querying that we used in part 1 of this guide. The NamedQuery is written using JPA-HQ and we use the createNamedQuery method to call it. The NamedQuery lives in the Entity class and has the annotation @NamedQuery.
If you understand JPA-QL, certainly you’ll not find any problem to use NamedQuery.

Criteria

Criteria API is the newest API in JPA 2. If you’re familiar with Hibernate, like me, certainly you liked this API in JPA 2.
As Criteria API is new, it deserves an unique post for it. Part 4 of this guide is exclusive for Criteria.

Best Practices

One of the most common question regarding querying in JPA is where to use them. The simple answer could be:

  • Native Qurery: When you need a specific command/resource from the database that a JPA-QL doesn’t offer
  • JPA-QL: When you have a static query
  • NamedQuery: When you have a static query that doesn’t change, use it instead Criteria
  • Criteria: When you have a dynamic query

This post ends here, but in the Part 4 we’re going to keep talking about querying, but we’re only talk about Criteria API.
If you have any question or comment, fell free to leave your message below. I hope this topic be useful for anyone else.

  1. April 23rd, 2010 at 05:17
    #1

    Hi Jair,

    I’m writing to you for Packt Publishing, the Publishers of computer related books.

    We are planning to publish a new book on Netbeans. While trying to look out for potential authors to write this book, I came across your profile and it seems that your expertise lie in this area. This gives me an impression that you could be a potential author for this book.

    Title: NetBeans Cookbook.
    It is planned to be a 300 page book targeted at Java developers who use NetBeans IDE.

    Prerequisite for readers: Previous experience of programming in Java. No previous experience of using NetBeans is necessary.

    To give you an idea about the way things works at Packt:

    - The editorial team at Packt works with the author through out the project.
    - We pay a royalty of 16% and an advance against it.
    - The marketing team at Packt ensures that the book is well promoted.
    - In its ongoing commitment to OpenSource, Packt donates a percentage of revenue generated by the book to the OpenSource project on which it is based. We have donated more than 150 000 dollars to various OpenSource projects since inception in 2004.

    Could you please let me know if you find it interesting to author this book?

    Thanks.

  2. Anthony
    May 9th, 2011 at 10:43
    #2

    Hi Jair Rillo,

    First of all, great tutorial for all.
    I just wondering if u have part 4 and 5?

    /Antony

  3. Fernando Correia
    July 26th, 2011 at 22:17
    #3

    Very good job on this series, Jair. It was very useful for me since I’m starting to learn about JPA.

TOP