McM
mcm@noway.es
Contact me: noway.es
Contact me

Java JPA hello world

JPA - Java Persistence API

The Java Persistence API is a simple programming model for entity persistence. It is included in the EJB3 standard and it tries to keep the advantage of the object programing when using databases.

There are several implementations:

  • Hibernate
  • TopLink
  • CocoBase
  • EclipseLink
  • OpenJPA
  • Kodo
  • JPOX
  • Amber

Current JPA version is 2.0. You can find here the JSR 317: JavaTM Persistence 2.0

Here I present an easy way to create a JPA java project using eclipseLink.

EclipseLink

The EclipseLink JPA provides developers with a standards based Object-Relational persistence solution with additional support for many advanced features. EclipseLink JPA provides advanced support for leading relational databases and Java containers.

You can find the specification here eclipselink .

Download EclipseLink from the eclipse web eclipseLink . There you will find different pacakages depending on what you want to develop. In the following post we will see how to manage eclipseLink with OSGI but the following example is a easy Java example.

EclipseLink Project

Defining the Entity

The first you must define is the entity model. This will be Greeting.java. This time is a really simple entity, see JPA specification to relate tables with the tags, manytomany and so on ...

package com.as.jpa.example.entity;


import java.io.Serializable;

@Entity
public class Greeting implements Serializable {
@Id @GeneratedValue private int id;
@Basic private String message;
@Basic private String language;

public Greeting() {}
public Greeting(String message, String language) {
     this.message = message;
     this.language = language;
}

public String toString() {
     return "Greeting id=" + id + ", message=" + message + ", language=" + language;
}
}

The columns of our table GREETINGS will be:

  • id
  • message
  • language

This will be mapped in the following way:

mysql> desc GREETING;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| ID       | int(11)      | NO   | PRI | NULL    |       |
| MESSAGE  | varchar(255) | YES  |     | NULL    |       |
| LANGUAGE | varchar(255) | YES  |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Defining persistence.xml

In this xml file, all the information about the database will be found. This case we are going to use mysql database, so the persistence.xml will be

<?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="hello-world" transaction-type="RESOURCE_LOCAL">
<class>com.as.jpa.example.entity.Greeting</class>

<properties>
<!--
Default database login using Oracle for EclipseLink's internal
connection pool, change this to access your own database.
-->
<!--
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
-->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test2" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="adm" />

<!--
The database platform is auto-detected by default, if you want to
set a specific platform this can be set.
-->
<!-- property name=""eclipselink.target-database" value="Oracle" / -->

<!-- Optimize database writes to use batching. -->
<property name="eclipselink.jdbc.batch-writing" value="JDBC" />

<!-- Avoids flush being triggered before every query execution. -->
<property name="eclipselink.persistence-context.flush-mode"
value="COMMIT" />

<!-- Configure connection pool. -->
<property name="eclipselink.jdbc.connections.initial" value="1" />
<property name="eclipselink.jdbc.connections.min" value="64" />
<property name="eclipselink.jdbc.connections.max" value="64" />

<!--
In JSE no server platform is used, if you wish to use this example
is a JEE server with JTA, then you need to set this.
-->
<!-- property name="eclipselink.target-server" value="WebLogic" / -->

<!-- Configure cache size. -->
<property name="eclipselink.cache.size.default" value="1000" />
<!-- If desired, this option would disable caching. -->
<!-- property name="eclipselink.cache.shared.default" value="false" /-->

<!--
If desired, this option would force a JDBC connection to be held for
the duration of an EntityManager, instead of returned to the pool in
between queries/transactions.
-->
<!--
property name="eclipselink.jdbc.exclusive-connection.mode"
value="Always" /
-->

<!--
Configure database to be created on startup if not already existing.
-->
<!--
property name="eclipselink.ddl-generation" value="create-tables" /
-->
<!-- To drop and replace existing schema this can be used. -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

<!-- Configure simple SQL logging for demonstration. -->
<property name="eclipselink.logging.level" value="FINE" />
<property name="eclipselink.logging.thread" value="false" />
<property name="eclipselink.logging.session" value="false" />
<property name="eclipselink.logging.exceptions" value="false" />
<property name="eclipselink.logging.timestamp" value="false" />
</properties>
</persistence-unit>
</persistence>

Just remark these lines of the xml:

<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test2" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="adm" />

Where the database name test2 and the database interaction are defined. The only thing you must do is to create a database call test2 and then , all the tables will be auto generated.

and the persistence unit name. With this name a persistence entity will be created in the JpaTest:

<persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">

If you want to use oracle database, xml properties would be:

<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="javax.persistence.jdbc.user" value="scott" />
<property name="javax.persistence.jdbc.password" value="tiger" />

Simple piece of code

In the class jpaTest.java you will see how can we interact with the entity using JPA.

The first thing is to create the entity, hello-world

void initEntityManager() {
     emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
     em = emf.createEntityManager();
}

Then, it is easy to interact with the database, just like a normal java Object

void create() {
     em.getTransaction().begin();
     Greeting g_en = new Greeting("hello world", "en");
     Greeting g_es = new Greeting("hola, mundo", "es");
     Greeting[] greetings = new Greeting[]{g_en, g_es};
     for(Greeting g : greetings) {
         em.persist(g);
     }
     em.getTransaction().commit();
}

void read() {
     Greeting g = (Greeting) em.createQuery(
             "select g from Greeting g where g.language = :language")
             .setParameter("language", "en").getSingleResult();
     System.out.println("Query returned: " + g);
}

You will need mysql libraries to access to the database.

Project and libraries

EclipseLink, mysql libraries and source can be download here .
It is just and eclipse project . Import it and run JpaTest java file main method.

have fun!

Share it!

Twitter Gmail Delicious Google Bookmarks Hotmail Yahoo Mail Share/Bookmark