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

 
 

Share on Google+Share on Google+

JPA read data from database example

Advertisement
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.


Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 11, 2009

Related Tutorials

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
Panneer
February 6, 2014
em.getTransaction().commit();

Hi , I am new to JPA. Your tutorial is really helpful for new bees. Thank you very much.I would like to have a question. is it mandatory to put em.getTransaction().commit(); for select query also?. Thank you.
DMCA.com