Monday, June 10, 2013

Make a query in JPA

Recently I was doing some discovery on JPA. It was a real fun. I was totally switching my mindset to work with different terminology of my current work which involve a lot of XML code. With JPA, XML is useless. Let's say I have a table called Book, and a POJO object mapped on this table through annotation in the following way:
   public class Book {

         @Id
         private Integer isbn;

         @Column
         private String name;

         // getter and setter
   }
When I'm making a query on this table, there 2 ways on doing this:
1st way is to do it in SQL style (take note on line 4):
   EntityManagerFactory emf = Persistence.createEntityManagerFactory("book");
   EntityManager em = emf.createEntityManager();
   em.getTransaction().begin();
   Query q = em.createQuery("select b from Book b");
   List list = q.getResultList();
   em.getTransaction().commit();
   em.close();
2nd way is to do it through object-oriented way (take note on line 5):
   EntityManagerFactory emf = Persistence.createEntityManagerFactory("book");
   EntityManager em = emf.createEntityManager();
   EntityTransaction tx = em.getTransaction();
   tx.begin();
   Book book = em.find(Book.class, 1);
   tx.commit();
   em.close();

Cool huh!?! Happy Programming @!

No comments: