Home Jpa Jpacrud JPA read data from database example
Questions:Ask|Latest



JPA read data from database example
Posted on: June 11, 2009 By Deepak Kumar
In this section, you will learn how to retrieve data from database using JPA.

JPA read data from database example

     

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.

  1. Again, you create a "JPARead.java" file

  2. Put the following text in this file.

  3. Read code (JPARead.java):
/**

*/
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.



Recommend the tutorial

Ask Questions?    Discuss: JPA read data from database example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
GhostRider
June 27, 2012
How to connect Remote datastore with JPA?

Hi, How to connect Remote datastore with JPA? Thanks, GhostRider