EJB3 tutorial, part 04: Introducing JPA
In the last post about EJB3 (phew, three months ego ...) we discussed the session beans' lifecycle callbacks. So far we know how to create a stateless (or stateful) session bean and call it from a standalone client. We used JBoss Tools for development.
In this post I would like to switch to Netbeans 6.8 and Glassfish which is nicly integrated with it. You can download it from netbeans.org. Choose the Java package (180MB), it will have everything you need. Also creating JEE projects seems to be a little bit easier and less confusing (and we want to learn EJB3 technology and not care about the tools). So, let's get to work.
First, create a new project:
- Go to File -> New Project ...
- Select Java EE -> Enterprise application and click finish (or next if you want to provide any more specific settings
After that add a session bean, name it Tasks. Make it stateless with local interface only. We will be connecting to it from a servlet, the same JVM, so we don't need a remote interface. Netbean should create a bean and an interface. We will fill that with methods soon.
Next add an entity. Wait, what's an entity? That's something new ...
JPA (Java Persistence API) introduces entities. They represent data that is persisted (in database). Don't think of entity as an object representation of database table. A particular entity may map all fields of particular table but doesn't have to. It may map only some fields or it may map more than one table at once. This might be useful when you map some old, legacy database.
From the pure Java point of view entity is a POJO + annotations. The full requirements for an entity bean can be found in JSR-220. For our learning purposes now we only need to remember that it represents data from database and it needs to have some kind of identifier.
Create entity in Netbeans. Call it task. Netbeans will warn you about no persistence unit. Click the button, select jdbc/sample data source, select "create and drop" and accept rest as defaults.
We've created an entity that will be managed within a new persistence unit. That persistence unit will use jdbc/sample data source (it's JNDI name of a default datasource provided by glassfish that uses a build in database Apache Derby). The create and drop tells the server to drop and recreate the tables everytime the application is redeployed. This way we can focus on object side of EJB3 and JPA and don't bother about the database itself (for now
.
You should see Task entity now. Add a new field called "name" to the class and apropriate getter and setter.
All the operations on entities are performed via EntityManger. The easiest way to obtain it is by injecting it into a bean. Go to our stateless bean and add a new field:
@PersistenceContext
private EntityManager em;
Now we want to prepare a few methods to see that it really works. Open the TasksLocal interface and add two methods:
public Task find(Long id); public void add(Task task);
Open the bean again and add the implementations:
public Task find(Long id) { return em.find(Task.class, id); } public void add(Task task) { em.persist(task); }
How to call our stateless bean? The simplest thing to do is to add a servlet. Call is Test and map it to /test. We need a refference to our stateless bean. We can obtain in via injection:
@EJB
private TasksLocal tasks;
Please see that we are reffering here to our stateless bean only via type (the local interface). You don't need too provide JNDI mapping here. However if you would like to have different the default names you can do it. Now uncomment the generated fragment. Instead of the line:
out.println(" <h1>Servlet Test at " + request.getContextPath () + "</h1> ");
Add the following lines:
Task task1 = new Task(); task1.setName("This is a test task"); tasks.add(task1); Task task2 = tasks.find(1l); out.println(task2.getName());
You can run the project now. Hit the servler (you may need to add "/test" to the URL). You should see "This is a test task" displayed in the browser.
Try to play with the project now. As a homework try to complete the following tasks:
- provide a method to remove a task (see JSR-220 for entity manager's method)
- in the servlet display a form to add a new task. Provide the doPost method in the servlet and persist the newly created task
- check how to view database from netbeans (hint: look for services tab). Check out how the database table have been created for tasks
- to go more forward, try to display all tasks from the database. Have a look how to perform an EJBQL query.
Here you can download the full project together with homework implemented.
Witam!
Jeśli mogę to dodam element tematycznej samoreklamy: http://lukaszantoniak.wordpress.com/2010/06/08/ejb-i-jpa/. Mam nadzieję, że wpis się spodoba:)
Pozdrawiam,
Łukasz
P.S. Bardzo dobry blog Mateuszu, czytam regularnie.