Java Persistence API
Java Persistance API (JPA) is a Java programming framework for managing relational data in Java applications. Many libraries and frameworks exist that implement JPA 2.0 specification (EclipseLink, TopLink, Hibernate...).
In this tutorial we will need:
- Apache Derby DB (here)
- EclipseLink JPA implementation
Using traditional SQL statements in Java seemed too heavy for development process, therefore JPA was intended to simplify the development of relational data applications. JPA maps the database entities and relations directly into Java classes.
JPA uses Java Persistence Query Language (JPQL) to make queries against entities stored in a relational database. JPQL queries are transformed to the syntax of SQL queries, but operate against entity Java objects instead with database tables.
Create new standard Java project named DerbyTest. Configure project build path to include derbyclient.jar, eclipselink.jar and javax.persistence_2.x.x.jar.
Create a class Person that will represent an entity in the database.
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
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(name="firstname")
private String firstname;
@Column(name="lastname")
private String lastname;
@Column(name="email")
private String email;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Person [firstname="+firstname+", lastname="+lastname+", email="+email+"]";
}
}
Main class
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class JpaDerbyTest {
private static final String PERSISTENCE_UNIT_NAME = "persons";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// create new person
em.getTransaction().begin();
Person p = new Person();
p.setFirstname("Brad");
p.setLastname("Pitt");
p.setEmail("bb.pp@ee.com");
em.persist(p);
em.getTransaction().commit();
Query q = em.createQuery("select p from Person p");
List<Person> personsList = q.getResultList();
for (Person person : personsList) {
System.out.println(person);
}
System.out.println("Size: " + personsList.size());
em.close();
}
}
Define persistence unit. JPA uses configuration of persistence unit in persistence.xml file. This file defines classes that will be represented as database entities and database connection properties such as driver and connection string (url+path to DB). Make sure you set correct path to DB.
The file persistence.xml should be placed inside src/META-INF directory. This is an example of persistence.xml file which was used in example above. When running application for the first time, the tables do not exist yet. EclipseLink JPA will create tables automatically, just unomment the two properties.
Once tables are successfully created, comment the lines, so they will not be created again next time (you will get error anyway).
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="persons" transaction-type="RESOURCE_LOCAL">
<class>si.matjazcerkvenik.derby.Person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby://localhost:1527//path/to/your/db/jpaTestDB;create=true" />
<property name="javax.persistence.jdbc.user" value="admin" />
<property name="javax.persistence.jdbc.password" value="admin" />
<!-- Important: EclipseLink should create the database schema automatically -->
<!-- UNCOMMENT NEXT LINES ON FIRST RUN!!! -->
<!-- <property name="eclipselink.ddl-generation" value="create-tables" /> -->
<!-- <property name="eclipselink.ddl-generation.output-mode" value="database" /> -->
</properties>
</persistence-unit>
</persistence>
Start Derby server:
$ java -jar $DERBY_HOME/lib/derbyrun.jar server start
Run the application.
To see results connect to the database and see the tables. You can do this directly from Eclipse (here).