In this section, you will learn how to retrieve data from database using JPA. Create a "JPARead.java" file and follows the following steps to reading data from database.


| /** * */ package roseindia; import java.util.Iterator; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; /** * @author Administrator * */ public class JPARead { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa"); EntityManager em = emf.createEntityManager(); try{ em.getTransaction().begin(); //Select all the record from student table Query query = em.createQuery("SELECT st FROM Student st"); List lst = query.getResultList(); Iterator it = lst.iterator(); while (it.hasNext()){ Student student = (Student) it.next(); System.out.print("Id:"+student.getId()); System.out.print(" Name:"+student.getSname()); System.out.println(" Course:"+student.getScourse()); } em.getTransaction().commit(); } catch(Exception e){ System.out.println(e.getMessage()); } finally{ em.close(); } } } |
4.Run and get the output in Console window.

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: JPA read data from database example
Post your Comment