Get started with JPA 2.0 (EclipseLink 2.1)

 
PHP Freelancer

Overview

Recently I just started playing with JPA (I used Hibernate and JDBC before). After reading some examples, I built a very simple program with JPA 2.0 (EclipseLink 2.1), Eclipse 3.5 Galileo and MySQL Server 5.1. I would like to summarize steps to build the program here.

Reference

  1. EclipseLink 2.1.0 download page
  2. Connector/J – MySQL JDBC driver
  3. A Java Persistence Example
  4. HelloWorld with JPA, TopLink and MySql

Steps

Download EclipseLink 2.1 and JDBC driver for MySQL Server 5.1

Use the above reference links to download EclipseLink 2.1 and MySQL 5.1 JDBC Driver. The JAR files we needed are eclipselink.jar, javax.persistence_2.0.1.v201006031150.jar and mysql-connector-java-5.1.13-bin.jar

Create Table

Use this SQL to create table bookbank for the example

DROP TABLE IF EXISTS `bookbank`;
CREATE TABLE `bookbank` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(45) NOT NULL DEFAULT '',
  `author` varchar(45) NOT NULL DEFAULT '',
  `price` double DEFAULT NULL,
  PRIMARY KEY (`id`)
)

Create a Connection Profile in Eclipse

A Connection Profile let you define a DB Connection and view Table Schema and Data in it. and the best part is it can generated Entity Bean for you according to connected DB Schemas!

  1. Start "Eclipse", choose "File" –> "New" –> "Other…". Select "Connection Profile" in the wizard
    image
  2. At New Connection Profile, select MySQL for Connection Profile Type. Enter the name of the connection profile. Click Next
    image
  3. At next page. You have to choose a driver definition. If you don’t already have a MySQL 5.1 driver definition, you have to create it here. Click the "New Driver Definition" button (red rectangle) to do that.
    You can jump to step 6 if you already have a MySQL 5.1 driver definition.
    image
  4. At New Driver Definition, select the driver template with System Version 5.1. Enter MySQL 5.1 as the driver name. Click "Jar List" tab
    image
  5. At "Jar List" tab, remove any existing jar listed here. Than click "Add JAR/Zip…" and choose the mysql-connector-java-5.1.13-bin.jar file you just downloaded.
    Then click "OK" to create the definition
    image
  6. Back to the "New Connection Profile" window, choose the MySQL 5.1 driver definition you just created. Enter the Database, URL, Username and password for the connection. Remember to check "Save password" for future connection. Click "Finish" to create the profiile.
    image

Create JPA Project in Eclipse

Next we have to create a JPA project in Eclipse.

  1. Start "Eclipse", choose "File" –> "New" –> "Project…". Select "JPA Project" in the wizard
    image
  2. At "New JPA Project", enter project name. Select <None> for "Target runtime". Click "Next" twice
    image
  3. At this page, use the values listed below:
    - "Platform": Generic
    - "JPA Implementation": Disable Library Configuration (we will add the EclipseLink library manually)
    - "Connection": Choose the connection profile you have just created
    Note: If you select "Add driver library to build path", the driver library used in your connection profile will be added to the project. Otherwise you need to manually add the correct driver library.
    image
  4. Click "Finish" to create the project

Create Entity Bean from DB Table

  1. In the JPA projec, add reference to eclipselink.jar, javax.persistence_2.0.1.v201006031150.jar libraries
  2. Right click on the JPA project, select "New" –> "Entities From Tables"
    image
  3. The connection profile should be automatically selected, choose the bookbank table. Click "Next" three times
    image
  4. At this page, choose "identity" for "Key generator". Click "Finish"
    image

Modify persistence.xml File

  1. Open the "persistence.xml" file inside folder "META-INF", replace the "persistence-unit" tag with the following content:
    <persistence-unit name="JpaTest" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        
        <class>Bookbank</class>
        
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_test" />
            <property name="javax.persistence.jdbc.user" value="MySQL_user_id" />
            <property name="javax.persistence.jdbc.password" value="MySQL_password" /> 
        </properties>
        
    </persistence-unit>

Create the testing console app

Now it’s time to test our JPA app! Let’s add a Java Class with the following code to the JPA project.

public class TestMain {
 
    public static void main(String[] args) {
        EntityManager em = Persistence
            .createEntityManagerFactory("JpaTest")
            .createEntityManager();
        EntityTransaction t = em.getTransaction();
 
        t.begin();
        Bookbank book = new Bookbank();
        book.setTitle("test title");
        book.setAuthor("test author");
        book.setPrice(123.456);
        em.persist(book);
        t.commit();
        
        t.begin();
        Bookbank resultBook = (Bookbank)em
            .createQuery("select b from Bookbank b order by b.id desc")
            .setMaxResults(1)
            .getSingleResult();
        System.out.println("Query result:");
        System.out.println("Id: " + resultBook.getId() 
                + ", title: " + resultBook.getTitle() 
                + ", author: " + resultBook.getAuthor() 
                + ", price: " + resultBook.getPrice());
        t.commit();
        
        em.close();
        System.exit(0);
    }
 
}

What the class do is simply insert a record with hardcoded values into bookbank table, and then select the newest record. We can start the "TestMain" class in Eclipse by right-clicking the class, "Run As" –> "Java Application"

image

 

Discussion

What do you think? Leave a comment. Alternatively, write a post on your own weblog; this blog accepts trackbacks [trackback url].

Comments
1.
On November 25th, 2010 at 6:46 pm, William said:
Thank you so much! Finally a good tutorial (and with my config!): simple, clear, step by step…! Good job! william
2.
On June 2nd, 2011 at 10:58 pm, aj said:
This is a very easy to understand tutorial, it was very helpful. Thank you, there arent many of such helpful tuts still available. Thanks a mil
3.
On September 14th, 2011 at 1:02 am, Moussa Kecibi said:
I have no word … Thank you so much
4.
On November 28th, 2011 at 6:46 pm, Dixon Kannur said:
simple and clear tutorial. Thank you so much…………!!!!!!!!
5.
On November 30th, 2011 at 5:41 am, Sam Shuh said:
I keep getting the exception: Exception in thread “main” javax.persistence.PersistenceException: No Persistence provider for EntityManager named TestJPA at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:89) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60) at TestMain.main(TestMain.java:8) What could be the problem? Thanks, Sam
6.
On January 8th, 2012 at 3:39 pm, Ankush said:
Good work..!!! Thank you..!!!:)
7.
On January 21st, 2012 at 6:46 pm, Jutta said:
thank you!!! with this example everyone can build his first JPA application
Leave a Reply