Develop java persistence example with Maven2

Getting Started with Maven2 : Download Maven2 from maven.apache.org, unzip the archive into your local directory.

Develop java persistence example with Maven2

Develop java persistence example with Maven2

     


Getting Started with Maven2 :
Download Maven2  from maven.apache.org, unzip the archive into your local directory. Here we are assuming that the local repository already exists.

Set the JAVA_HOME variable to point to the JDK installation directory and MAVEN_HOME to point to the Maven directory and add the MAVEN_HOME/bin to the PATH environment variable.

To test, whether the path has been set properly. Type mvn -version on the command prompt.

C:\>mvn -versionMaven 
version: 2.0.7Java version:1.5.0OS name: ?windows 2000? version: ?5.0? arch:?x86?

Developing java presistence example with Maven2

Here I will show, how to build a very simple example that uses java persistence API. Maven2 highly simplifies the build process, all the required libraries are downloaded automatically only when it really requires.

Directory Structure of the example: Our application must maintain a directory structure understandable by the maven project build tool. It is shown below:

Our Application includes: Our application includes the source folder "src" and an pom.xml file. Source folder contains java files, here HelloWorld.java and Message.java files are contained in the hello folder. Resource folder exists parallel to the java folder inside the main folder and contains  log4j.properties file and the META-INF folder. META-INF folder contains persistence.xml file. "pom.xml" is the main file for the maven build system that includes information  about the tools required to build the application. 

1. Create a java class (lets take it Message.java ), where you map java class/properties to database table/fields. Java persistence annotations will do this job for us:

package hello;

import javax.persistence.*;

@Entity
@Table(name = "MESSAGES")
public class Message {

@Id @GeneratedValue @Column(name = "MESSAGE_ID")
private Long id;

@Column(name = "MESSAGE_TEXT")
private String text;

@ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "NEXT_MESSAGE_ID")
private Message nextMessage;

public Message() {}

public Message(String text) {
this.text = text;
}

public Long getId() {
return id;
}

private void setId(Long id) {
this.id = id;
}

public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}

public Message getNextMessage() {
return nextMessage;
}

public void setNextMessage(Message nextMessage) {
this.nextMessage = nextMessage;
}

}

Here "Message" class is mapped to "MESSAGES" table, "id", "text" and "nextMessage" properties - to "MESSAGE_ID", "MESSAGE_TEXT" and "NEXT_MESSAGE_ID" fields.

2. Now create a simple program ( HelloWorld.java ) that uses persistent "Message" object:

HelloWorld.java

package hello;

import java.util.*;
import javax.persistence.*;

public class HelloWorld {

public static void main(String[] args) {

// Start EntityManagerFactory
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("helloworld");

// First unit of work
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();

Message message = new Message("Hello World with JPA");
em.persist(message);

message = new Message("This is message 2");
em.persist(message);

message = new Message("This is message 3");
em.persist(message);


tx.commit();
em.close();

// Second unit of work
EntityManager newEm = emf.createEntityManager();
EntityTransaction newTx = newEm.getTransaction();
newTx.begin();

List messages =
newEm.createQuery("select m from Message m order by m.text asc").getResultList();

System.out.println( messages.size() + " message(s) found:" );

for (Object m : messages) {
Message loadedMsg = (Message) m;
System.out.println(loadedMsg.getText());
}

newTx.commit();
newEm.close();

// Shutting down the application
emf.close();
}

}

This example does not refer to any persistent framework directly. Instead, it uses symbolic names to access the framework in indirect way. In the above mentioned example we have used "helloworld" name to refer to the ORM framework. 

3. In this example we used Hibernate (http://hibernate.org) as persistence framework and hsqldb (http://hsqldb.org) as database. Let's take a look at the hibernate configuration file (persistence.xml) where we describe "helloworld" factory:

persistence.xml

<persistence 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"
version="1.0">

<!-- persistence.xml -->

<persistence-unit name="helloworld">

<!-- The provider only needs to be set if you use several JPA providers -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>

<properties>
<!-- Scan for annotated classes and Hibernate mapping XML files -->
<property name="hibernate.archive.autodetection" value="class, hbm"/>

<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>

<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>

<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:file:persistence-db/test"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>

<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
</properties>
</persistence-unit>

</persistence>

persistence.xml should be located on your CLASSPATH within META-INF directory. "hibernate.hbm2ddl.auto" property will take care of creating database table automatically.

4. Create a Maven2 file i.e. pom.xml file, responsible for downloading all dependent libraries, building correct CLASSPATH for the project and running the example. POM is the fundamental unit of work in Maven. It is an xml file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. For example, the build directory, which is ?target?, the source directory, which is ?src/main/java? the test source directory, which is ?src/main/test? and so on. POM also contains the goals and plugins. So, while executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal. Some of the configuration that can be specified in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists and such can also be specified. 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project>
<modelVersion>4.0.0</modelVersion>

<groupId>persistence-deps</groupId>
<artifactId>persistence-deps</artifactId>
<version>1.0</version>

<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.0.4</version>
</dependency>

<dependency>
<groupId>hsqldb</groupId> 
<artifactId>hsqldb</artifactId> 
<version>1.8.0.7</version> 
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.2.ga</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.2.1.ga</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.2.1.ga</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.0.beta9a</version>
</dependency>

<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>

<build>
<defaultGoal>compile</defaultGoal>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>

<configuration>
<mainClass>hello.HelloWorld</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<!--
<repositories>
<repository>
<id>scriptlandia-repo</id>
<name>Scriptlandia Maven2 repository</name>
<url>http://scriptlandia-repository.googlecode.com/svn/trunk/tools</url>
</repository>
</repositories>
-->
</project>


4. Open the command prompt. Go inside the project directory of your application (MyApplication in this case) and run the "mvn compile exec:java" command.

C:\MyApplication >mvn compile exec:java

After successfully running the command, your command prompt will display the output on the console shown below: 

Hibernate:
insert
into
MESSAGES
(MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID)
values
(null, ?, ?)
Hibernate:
call identity()
Hibernate:
insert
into
MESSAGES
(MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID)
values
(null, ?, ?)
Hibernate:
call identity()
Hibernate:
insert
into
MESSAGES
(MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID)
values
(null, ?, ?)
Hibernate:
call identity()
Hibernate:
select
message0_.MESSAGE_ID as MESSAGE1_0_,
message0_.MESSAGE_TEXT as MESSAGE2_0_,
message0_.NEXT_MESSAGE_ID as NEXT3_0_
from
MESSAGES message0_
order by
message0_.MESSAGE_TEXT asc
3 message(s) found:
Hello World with JPA
This is message 2
This is message 3

Aug 21, 2007 3:18:06 AM org.hibernate.impl.SessionFactoryImpl close
INFO: closing
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 34 seconds
[INFO] Finished at: Tue Aug 21 03:18:06 GMT+05:30 2007
[INFO] Final Memory: 6M/11M
[INFO] ------------------------------------------------------------------------

On building successfully, our application displays the messages given below on the console:

Hello World with JPA
This is message 2
This is message 3