Tuesday, July 7, 2015

Persisting (to MySQL) java objects using EclipseLink - JPA

This article explains how to create a JPA application using EclipseLink. JPA stands for Java Persistence API a standard that defines how to persist java objects directly to a data base. The other popular java standard is JDO. EclipseLink is an implementation of JPA standard done by Oracle and open sourced. TopLink is their paid product.
I tried JPA (I might use JPA and EL interchangeably, please read based on context) with several databases, including Oracle, MySQL, Derby, Mongo MS-SQL. Not just that I tried JPA with java objects are that are not designed, i.e. java objects are created during run time and persisted them to database (yes, you are right, tables need to be created during run time and JPA gives you an option to do that too) But most of that stuff will explain in later blogs.
Current blog is a simple JPA based stand alone program that persists a java objects to MySQL database.

I am using Mac OS X Yosemite (version 10.10.3) and maven version 3.1.1 and JDK 1.7.
If you don't have maven or JDK please install them first and come back.

maven archetype are kind of templates that will allow you to create pre-configured (or filled) projects. So number 623 represents a sample maven project.
623: remote -> org.apache.maven.archetypes:maven-archetype-quickstart (An archetype which contains a sample Maven project.  107 - is simple JPA, EclipseLink based project. )



gputty ~/temp/blog$ mvn archetype:generate   
then keep entering appropriate values.  Except groupId and artifactId you can chose default values. 
OR you can simply give the type directly and all parameters in one line and create it like below. 


 mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=com.gopi.jpa -DartifactId=SimpleJPAProject -Dversion=1.0.0   
 cd SimpleJPAProject   
 mvn test  
 ls -al   
 mvn eclipse:eclipse   
 ls -al  

Now you have a basic maven project is ready. 'mvn eclipse:eclipse' command will add .classpath and .project files that help to import this project directly to Eclipse IDE. Now you can open Eclipse and File --> import and point to this directory and import it.

To be continued...