Showing posts with label pojo ejb3.0 jpa orm java example howto. Show all posts
Showing posts with label pojo ejb3.0 jpa orm java example howto. Show all posts

Saturday, February 03, 2007

EJB 3.0 Outside the Container, Inside the JVM - Part 3: Wrapping the Model

Welcome to part three of my blog on using EJB3.0 / JPA and Derby inside the JVM. The previous parts can be found here and here.

We're almost ready to go. However, we still need to wrap our domain model with a facade in order to manage interactions with it and prevent any JPA specific code creeping outside the model boundaries. We can do this by placing a session bean in front of our Claim POJO. (Why a session bean when we're not really going to use this within a Java EE container? Aha! Maybe something will come along in a later posting...)

We'll start by creating a new POJO class called ExpensesTrackerService. To make it a Stateless Session bean we simply the @Stateless annotation. We also need to add the following dependency to the project so that we can get the imports needed:

Now we need to provide a means to address and manage the Claim entity. In JPA this is via the EntityManager which we obtain via an EntityManagerFactory


Now that we have an EntityManager we can use it within our CRUD methods. Here:

Here:

And here:

Now all we have to do is build our maven project (run the jar:install maven goal) which will also copy the resulting jar containing our wrapped model to the repository. In the next entry we'll use it from within our Swing client

EJB 3.0 Outside the Container, Inside the JVM - Part 2: Configuring JPA Declaratively

Welcome to part two of this blog entry introducing using EJB3.0 inside the JVM. Click here to view the first part.

As we've seen, JPA can use our annotated POJO model to create a database for us, but first we need to give it some information on how to do it. We provide this information in a file called persistence.xml. Let's create a blank file with this name in {PROJECT_HOME_DIR}/expenses-tracker-model/
resources/META-INF/.
We also need to let maven know where this is so we add the following to our project.xml file:


This entry ensures that this file will be included on the build classpath.

Now lets add the content to persistence.xml. We'll start at the top:


The persistence-unit tag tells JPA about our (future) database. A single persistence.xml file can have mulitple persistence units but we will keep things simple and just stick to one. Attributes to this tag provide the persistence unit name (which we'll use to refer to it later in code) and the transaction-type. (We have the default). We'll only need the former as we'll see later on.

Enclosed within this top level is the tag which tells JPA which implementation will provide the actual persistence functionality - the "provider" tag. Our example uses the Toplink ORM tool but we could swap this to something like Hibernate simply by changing the contents of this tag.

Finally there is the tag where we declare our new entity class - "class". This tells JPA that we want it to be considered as part of this persistence unit. (Note: if you find JPA doing things you don't expect, check that you have listed all the classes you wish it to be aware of here. It can't work with what it has no idea about!)

Ignore the commented out tags. If you really want to know what they do then just google or yahoo! them.

This is all well and good but clearly my file is a little more complicated. Toplink will need some additional information in order to do its job and we can put this in this file as well. These go within the "properties" tags. You can see below that we use these to tell Toplink the driver class to use, the url for the database connection and well get to the third piece of magic later.

Monday, January 29, 2007

EJB 3.0 Outside the Container and Inside the JVM - Part 1: The POJO Model

NOTE: This is a more truncated version of an entry I started previously. The aim is to keep it simpler and to actually finish this it...

ANOTHER NOTE: I use Netbeans. It's not popular but I like it. If you don't have Netbeans you'll still be able to follow this series but won't be able to drag and drop a Swing UI in part 4 using Matisse. My heart bleeds...

EJB 3.0 and JPA 1.0 have made it easy for people like me (RDBMS-phobics) to persist our O-O domain models. What's more, Derby (aka JavaDB) has made it easy to have within-JVM RDBMS persistence that is transparent to the user of your thick client application. What follows is a simple example application I wrote to learn some of the basic concepts (and also track my expenses claims)

Step 0: Setting up my project.

I like Maven; Maven 1.0.x to be precise. Before anything else I set up a basic maven project called "expenses-tracker-model" in the standard fashion:


You'll also need to manually get hold of the JPA and Derby Jars (toplink-essentials.jar, derby-10.1.jar and javaee-9.jar) and place them in your repository wherever you see fit.

Step 1: Coding the Domain Model

I like to model in OO land. My model is very simple - a single, serializable POJO class called "Claim" - which will eventually map to a single Derby table called "CLAIM". I create my java class and add attributes as follows:
private Long id;
private String refNumber;
private String projectCode;
private String description;
private Date dateFrom;
private Date dateTo;
private String status;
private Date submitDate;
private Date paidDate;
private Long totalClaimed;
private Long totalFromCurrentAccount;
I now need to add the annotations which will allow JPA to work its magic. First I tell the class that it is an entity (i.e. will be represented in the RDBMS) with the following annotation:
import javax.persistence.Entity;
...
@Entity
public class Claim implements Serializable {
...
The compiler is now clever enough to know that, unless told otherwise, the attributes on this class will be represented as columns in our table. That's how EJB 3.0 works. It assumes the default unless you tell it different. Very handy.

The observant amongst you will realise that we most likely need a primary key. You're right. We need to declare which will be our primary key field and how we will work with it. This is done with the @Id annotation. The @GeneratedValue annotation tells JPA that we'dlike the RDBMS to auto generate our PKs for us (which makes things even easier at our O-O end):
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
...
/** Unique, datastore generated id */
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
Finally, because we have java.util.Date fields, we need to provide some extra information about these for JPA also:
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
...
@Temporal(TemporalType.TIMESTAMP)
private Date dateFrom;
We're nearly there. Another quick IDE aided step to encapsulate our attributes with some getters and setters and we're ready to go. You should now have something like this:
package com.andrewharmellaw.exptracker.model;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Claim implements Serializable {

/** Unique, datastore generated id */
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String refNumber;

private String projectCode;

private String description;

@Temporal(TemporalType.TIMESTAMP)
private Date dateFrom;

@Temporal(TemporalType.TIMESTAMP)
private Date dateTo;

private String status;

@Temporal(TemporalType.TIMESTAMP)
private Date submitDate;

@Temporal(TemporalType.TIMESTAMP)
private Date paidDate;

private Long totalClaimed;

private Long totalFromCurrentAccount;

/** Creates a new instance of Claim */
public Claim() {

}

public Long getId() {
return id;
}

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

public String getRefNumber() {
return refNumber;
}

public void setRefNumber(String refNumber) {
this.refNumber = refNumber;
}

public String getProjectCode() {
return projectCode;
}

public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Date getDateFrom() {
return dateFrom;
}

public void setDateFrom(Date dateFrom) {
this.dateFrom = dateFrom;
}

public Date getDateTo() {
return dateTo;
}

public void setDateTo(Date dateTo) {
this.dateTo = dateTo;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public Date getSubmitDate() {
return submitDate;
}

public void setSubmitDate(Date submitDate) {
this.submitDate = submitDate;
}

public Date getPaidDate() {
return paidDate;
}

public void setPaidDate(Date paidDate) {
this.paidDate = paidDate;
}

public Long getTotalClaimed() {
return totalClaimed;
}

public void setTotalClaimed(Long totalClaimed) {
this.totalClaimed = totalClaimed;
}

public Long getTotalFromCurrentAccount() {
return totalFromCurrentAccount;
}

public void setTotalFromCurrentAccount(Long totalFromCurrentAccount) {
this.totalFromCurrentAccount = totalFromCurrentAccount;
}
}

Right, that's the dull part done. Now we can get to the fun part - using this POJO to auto-create our database. That's in the next post in this series...