In the last chapter we have discussed the fundamental concepts of Java Persistence API. Now let use see a JPA Example. It simply inserts a record into an existing database and then fetching the inserted data using JPA. We are starting our discussion with creation of database onwards.We are using Apache OpenJPA as JPA implementation.
Tools & Software needed
1)Eclipse Indigo – Download Link
2)MySQL Server 5.x – Download Link
3)SQLYog Community edition – Download Link
4)Java EE SDK 1.6 – Download Link
5)Open JPA Library – Download Link
JPA Example
The example we are discussing here inserts an object data into database and then reading the data.We need to have all the tools ready in our development environment . Lets start the discussion with creation of database.
Step 1) Create Database ‘JPASAMPLEDB’ either from MySQL command line client or from SQLYog.
CREATE DATABASE `JPASAMPLEDB` ;
Step2)Create table ‘STUDENT’ int ‘JPASAMPLEDB’.
USE JPASAMPLEDB;
CREATE TABLE `STUDENT` (
`id` INT(11) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`level` VARCHAR(20) NOT NULL,
PRIMARY KEY (`id`)
)
Step 3)Open eclipse in a suitable workspace.
Step 4)Create a JPA project in eclipse(File–>New–>JPA Project).
Step 5)Press Next button .Press Next again for the new window . Now we need to configure the JPA Library. We are configuring the JPA libraries already downloaded. Also we need to include the MySQL connector jar to the library.Click on the Manage libraries icon highlighted.
Step 6) Press New then give suitable name to the library.Then press OK
Step 7 )Now we need to add the jar files to library.We are adding the openjpa-all-2.2.2 and all dependent jars in the lib folder of open JPA Binary .Also we need to include the MySQL Connector Jar.
Step 8)Add jars and press OK
The jar files included in the project are :
mysql-connector-java-5.0.8-bin
openjpa-all-2.2.2
asm-3.2
commons-beanutils-1.8.3
commons-collections-3.2.1
commons-dbcp-1.4
commons-lang-2.4
commons-logging-1.0.4
commons-pool-1.5.4
derby-10.8.2.2
geronimo-jms_1.1_spec-1.1.1
geronimo-jpa_2.0_spec-1.1
geronimo-jta_1.1_spec-1.1.1
geronimo-validation_1.0_spec-1.1
org.apache.bval.bundle-0.3-incubating
serp-1.14.1
Most of the jar files listed above are not needed in this particular example. We will be doing complex examples in the coming chapters. There we need some of these jar files.
Step 9)Now select the check box against the newly created library and press Finish
Step 10 )Create packages in src folder of project.
Step 11)Create an entity class Student.java . The mappings are done in entity class itself. Primary key generation strategy is AUTO
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity(name = "Student")
@Table(name="student")
public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String level;
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@Column(name = "name")
public void setName(String name) {
this.name = name;
}
public String getLevel() {
return level;
}
@Column(name = "level")
public void setLevel(String level) {
this.level = level;
}
public String toString(){
return "ID = "+getId() + " ; Name : = "+getName() +" ; Level : = "+getLevel();
}
}
Step 12)Create a class to insert and read data using JPA.The class has two methods other than main , one is to insert data and the other is to read the inserted data.Both transactions are done with same EntityManager instance.
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import com.jpa.entity.Student;
public class JPASample {
private EntityManager entitymanager;
public static void main(String[] args) {
JPASample sample = new JPASample();
sample.getEntityManager();
sample.doInsert();
sample.doRead();
}
public void getEntityManager() {
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("OpenJPASample");
entitymanager = entityManagerFactory.createEntityManager();
}
public void doInsert() {
if (null != entitymanager) {
EntityTransaction transaction = entitymanager.getTransaction();
Student student = new Student();
student.setName("Noby");
student.setLevel("H");
transaction.begin();
entitymanager.persist(student);
transaction.commit();
System.out.println("The object is persisted...");
}
}
public void doRead() {
if (null != entitymanager) {
EntityTransaction readTransaction = entitymanager.getTransaction();
readTransaction.begin();
Query query = entitymanager
.createQuery("select student FROM Student student");
List list = query.getResultList();
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Student student = (Student) iterator.next();
System.out.println("Student Details : " + student);
}
readTransaction.commit();
}
}
}
Step 13) Edit the persistence.xml in src\META-INF\persistence.xml
User name , Password , and other configuration properties needs to be provided.
Step 14)Now run the JPASample.java
Output
The object is persisted…
Student Details : ID = 1 ; Name : = Noby ; Level : = H
See Related Discussions
JPQL
Caching
Locking in JPA
Relational Mappings in JPA
can you provide the persistence.xml i got the error. i think something wrong in my persistence.xml file.