Home Jpa Jpacrud JPA read data from database example



JPA read data from database example
Posted on: June 11, 2009 at 12:00 AM
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.


Related Tags for JPA read data from database example:
javacdatabasefiledatajpareadcreatetabtoreadingbasewseilepsareafrominasmparpsjadstepasesatllfolloweaandarwingvassthstepsavstabndomolo


More Tutorials from this section

Ask Questions?    Discuss: JPA read data from database example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

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.