Still using pure JDBC (Java DataBase Connectivity) drivers? Having hard times while refactoring SQL? You have to try out one of the ORM (Object-Relational Mapping) solutions. Two most-known are Hibernate and EclipseLink. In this article I’ll show you step-by-step how to run your first EclipseLink code using Eclipse and PostgreSQL.
1. Install PostgreSQL, pgadmin3 (gui manager), set up user and database.
Create user “testuser” with password “testpassword” and database for him: “testdb”:
In console:
sudo -u postgres createdb testdb sudo -u postgres createuser testuser Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) y Shall the new role be allowed to create more new roles? (y/n) n sudo -u postgres psql
In psql:
alter user testuser with password 'testpassword' \q
After those operations you should be able to connect to db via pgadmin3.
2. Get Eclipse IDE for Java EE Developers ( http://www.eclipse.org/downloads/ ).
3. Download the newest version of EclipseLink ( http://www.eclipse.org/eclipselink/downloads/index.php ).
4. Download the newest version of ODBC driver ( http://jdbc.postgresql.org/download.html ).
5. Create new JPA project with name “eclipselinktest”.
6. Ensure you have EclipseLink, PostgreSQL JDBC driver and javax.persistence API (from eclipselink.zip -> eclipselink/jlib/jpa/) in your buildpath.
7. In your META-INF/persistence.xml file type:
org.eclipse.persistence.jpa.PersistenceProvider com.codesmuggler.model.User
8. Create 2 classes (com.codesmuggler.model.User and com.codesmuggler.Main):
com.codesmuggler.Main:
package com.codesmuggler; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.eclipse.persistence.jpa.JpaEntityManager; import org.eclipse.persistence.queries.ReadAllQuery; import org.eclipse.persistence.sessions.UnitOfWork; import org.eclipse.persistence.sessions.server.ServerSession; import com.codesmuggler.model.User; public class Main { private static final String PERSISTENCE_UNIT_NAME = "eclipselinktest"; private final EntityManagerFactory entityManagerFactory; private final EntityManager entityManager; private final JpaEntityManager jpa; private final ServerSession serverSession; public Main() { // initializations entityManagerFactory = Persistence .createEntityManagerFactory(PERSISTENCE_UNIT_NAME); entityManager = entityManagerFactory.createEntityManager(); jpa = (JpaEntityManager) entityManager.getDelegate(); serverSession = jpa.getServerSession(); } public UnitOfWork acquireUnitOfWork() { return serverSession.acquireClientSession().acquireUnitOfWork(); } public static void main(String[] args) { Main main = new Main(); UnitOfWork uow = main.acquireUnitOfWork(); // create 2 new users User codesmuggler = new User(); codesmuggler.setName("codesmuggler"); codesmuggler.setAge(77); User helloKitty = new User(); helloKitty.setName("helloKitty"); helloKitty.setAge(3); // register users in UnitOfWork uow.registerNewObject(codesmuggler); uow.registerNewObject(helloKitty); // commit transaction uow.commit(); // now try to read our users ReadAllQuery raq = new ReadAllQuery(User.class); @SuppressWarnings("unchecked") Listusers = (List ) uow.executeQuery(raq); for (User u : users) { System.out.println("USER: " + u.getName() + " ID: " + u.getId() + " AGE: " + u.getAge()); } } }
com.codesmuggler.model.User:
package com.codesmuggler.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; // annotations tells that this is an entity // which should be persisted @Entity // table name have to be changed to "users" // it should be "users" because keyword "user" is restricted in PostgreSQL @Table(name = "users") public class User { public static final String FIELD_ID = "id"; public static final String FIELD_NAME = "name"; public static final String FIELD_AGE = "age"; // this field is primary key and its value have to be generated using // strategy @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // this field in db have to be unique @Column(unique = true) private String name; private int age; public int getId() { return id; } protected void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
9. Run the Main class and see the result:
USER: codesmuggler ID: 1 AGE: 77 USER: helloKitty ID: 2 AGE: 3
————
What just happened?
EclipseLink using UnitOfWork saved the data in PostgreSQL database. After that all users were fetched to print them out. As you see, you didn’t have to use any SQL statements to do that. It’s only the tip of the iceberg – the possibilities of EclipseLink are much greater. In the future I’ll try to describe them.
PS EclipseLink 2.3.0 and JPA 2.0.3 are used.
Nice post. I was curious why you dropped down to native EclipseLink classes (from JPA) to perform queries instead of using the standard JPA APIs?
-Blaise
It’s article about EclipseLink so I just wanted to use its classes. The other thing is that EclipseLink has also nice API. You acquire UnitOfWork and can do everything in transaction.