Setting up an Eclipse JPA Project based on Java SE and using Hibernate

This article describes the use of Hibernate with an Eclipse Europa JPA Project. I'm basing this on using JPA outside of an EJB3 Container.

Pre-requisite Reading

Pre-requisite Software

Setting up the Eclipse Environment

Before we can create the eclipse project, we need to set up a couple of things

Configure a JPA Implementation Library

Hibernate is our JPA Implementation, so we set up an Eclipse User Library. The main pain is determining which jars you need. We need Hibernate Core and the Hibernate EntityManager. You might think from the Hibernate Site that you also need Hibernate Annotations but in fact thats included in the Entity Manager package.

  1. Choose Windows -> Preferences from the main menu. Then select Java -> Build Path -> User Libraries. Select New ... , name the library Hibernate, and click OK.
  2. In the Users Libraries pane select the Hibernate library and the select Add JARS...
  3. Click the Classpath tab and then click Add JAR/Folder and locate the following JAR files:

Configure a Database Connection

This is straightforward stuff. If it is new to you. See the Data Tools Platfrom (DTP) Getting Started Guide on the Eclipse site.

 

 

 

Creating the JPA Project

We're now ready to run through a New Project Wizard to create our JPA project.

 

Step 1

JPA Project Wizard Step 1

Step 2

JPA Project Wizard Step 2

Step 3

JPA Project Wizard Step 3

Step 4

 

Note in this screenshot that we specify our preconfigured database connection and JPA Implementation Library.

JPA Project Wizard Step 4

Post Wizard Configuration

Configuring Persistence.xml

You will at least need to add your class information, your persistence-unit name and Hibernate specific properties.

Required Hibernate properties are:-

 

<?xml version="1.0" encoding="UTF-8"?>
  <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/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_1_0.xsd">
  <persistence-unit name="AccountSubscription">
    <mapping-file>META-INF/orm.xml</mapping-file>
    <class>com.mftltd.account.Account</class>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
        <property name="hibernate.connection.url"
            value="jdbc:mysql://localhost:3306/subscription" />
        <property name="hibernate.connection.username" value="root" />
        <property name="hibernate.connection.password" value="password" />
    </properties>
  </persistence-unit>
</persistence>

Configuring Log4J

You will want to configure a log4j.xml file in your classpath as Hibernate writes a lot of useful debug info. See a sample.

Time to write some code

Its plain sailing, you just have to write your code! Just for completeness, I'll just follow up with a basic Account class and an Account Repository class which will persist the account to our database. Also attached is the DDL to create the Account table, although you could let JPA auto-create the tables

 

create_account_table.java

DROP TABLE IF EXISTS `subscription`.`account`;
CREATE TABLE `subscription`.`account` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `email` varchar(128) NOT NULL,
   `firstname` varchar(128) NOT NULL,
   `lastname` varchar(128) NOT NULL,
   `company` varchar(128) NOT NULL,
   `phone` varchar(128) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

account.java

package com.mftltd.account;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "account", schema = "subscription")
public class Account implements Serializable {
private static final long serialVersionUID = -7201186159122319296L;

@Id
@GeneratedValue(strategy=IDENTITY)

private int id;
private String email;
private String firstname;
private String lastname;
private String company;
private String phone;

public String getEmail() {
  return email;
}
public void setEmail(String email) {
  this.email = 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 getCompany() {
  return company;
}
public void setCompany(String company) {
  this.company = company;
}
public String getPhone() {
  return phone;
}
public void setPhone(String phone) {
  this.phone = phone;
}
public int getId() {
  return id;
}
public void setId(int id) {
  this.id = id;
}
}

AccountRepository.java

package com.mftltd.account;

import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;

public class AccountRepository {
public static void main(String args[]) {
try {
  // SetUp
  EntityManagerFactory emf = Persistence.createEntityManagerFactory("AccountSubscription");
  EntityManager em = emf.createEntityManager();
  EntityTransaction et = em.getTransaction();
  et.begin();
  // Create our Account Record
  AddAccount(em);
  // Commit and Clean-Up
  et.commit();
  em.close();
  emf.close();
} catch (Exception ex) {
  System.out.println(ex.getMessage());
  ex.printStackTrace();
}
}

public static void AddAccount(EntityManager em) {
  Account acc = new Account();
  acc.setEmail("dacarey@gmail.com");
  acc.setCompany("2YP Partners Ltd");
  acc.setPhone("07769 697996");
  acc.setFirstname("David");
  acc.setLastname("Carey");
  em.persist(acc);
}

 

Appendix - Sample log4j.xml

This shows how to get Hibernate to display SQL statements

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="console" class="org.apache.log4j.ConsoleAppender">
   <param name="Target" value="System.out"/>
   <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
   </layout>
</appender>
<!-- Limit the org.hibernate category to INFO since logging to DEBUG affects performance badly -->
<category name="org.hibernate">
   <priority value="INFO"/>
</category>
<!-- Log SQL statements-->
<category name="org.hibernate.SQL">
   <priority value="DEBUG"/>
</category>
<!-- Otherwise we will only display ERROR messages -->
<root>
   <priority value ="ERROR" />
   <appender-ref ref="console" />
</root>

</log4j:configuration>
}