NetBeans 6.0 | A little JPA Example

In this post I’d like to show you how to use JPA in NetBeans within a Java SE application. First of all you have to create a database and call it something like TestDB. I called my database ‚Medienverwaltung‘ because I did a small JPA-tutorial from the new Javamagazin which had exactly the same database.

Create a very simple table without any references on other tables and call it ‚ACTOR‘. That’s all you need for a first little JPA test. Now, create a JavaApplication in NetBeans. I called my application ‚JPAGenTest‘.

The next step is to generate an Actor-Entity-Class which will map the data into the corresponding ‚ACTOR‘-table in your database. A lot of errors will show up. That’s because the necessary libraries are still missing.

You can import them by configure your libriaries within the IDE or you create the persistent-unit and the libs will be imported automatically. You have to create this persistent unit anyway so I’ve decided to create it to import the missing libs.

Now all errors are gone and you will be able to create more JPA functionality. The next step is to implement a Manager-Class which handles the JPA persistence-context. That means this class is responsible to provide CRUD functionality for your actor-instances and to communicate with your database.

I’ve named this kind of class ‚ActorManager‘ and implemented the following typically methods to interact with my database:

  • createActor
  • findById
  • findByFirstname (NamedQuery)
  • findByLastname (NamedQuery)
  • updateActor
  • removeActor
  • getAll
  • removeAll

NamedQuery is a JPA-Feature which was automatically created by NetBeans when you’ve created your Enitity-Class. It’s a simple JPQL statement which usually will be used more often in your application.

Here is the code from the ActorManager:


package com.blogspot.sageniuz;

import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

/**
* Actor-Manager
* @author Claus Polanka
*/
public class ActorManager {

private EntityManager em;

public ActorManager(EntityManagerFactory emf) {
em = emf.createEntityManager();
}

public void createActor(ActorGenEntity actor) {
em.getTransaction().begin();
em.persist(actor);
em.getTransaction().commit();
}

public ActorGenEntity findById(Integer id) {
return em.find(ActorGenEntity.class, id);
}

public List findByFirstname(String firstname) {
Query query = em.createNamedQuery("ActorGenEntity.findByFirstname");
query.setParameter(firstname, em);
List listOfActors = query.getResultList();
return listOfActors;
}

public List findByLastname(String lastname) {
Query query = em.createNamedQuery("ActorGenEntity.findByLastname");
query.setParameter(lastname, em);
List listOfActors = query.getResultList();
return listOfActors;
}

public void updateActor(ActorGenEntity actor) {
em.getTransaction().begin();
em.merge(actor);
em.getTransaction().commit();
}

public void removeActor(ActorGenEntity actor) {
em.getTransaction().begin();
em.remove(actor);
em.getTransaction().commit();
}

public List getAll() {
Query query = em.createQuery("select a from ActorGenEntity a");
List list = query.getResultList();
return list;
}

public void removeAll() {
em.getTransaction().begin();
Query query = em.createQuery("select a from ActorGenEntity a");
List list = query.getResultList();
Iterator it = list.iterator();
while (it.hasNext()) {
ActorGenEntity actor = it.next();
em.remove(actor);
}
em.getTransaction().commit();
}

public void close() {
em.close();
}
}

Testing the application is the next thing to do, so let’s create a JUnit test-clase. Before you start implementing it check if you have already imported you database-driver or you will get an exception when executing your JUnit-test.

Here is the code for my test-class:


package com.blogspot.sageniuz;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import junit.framework.TestCase;

/**
* CRUD Test for Actor-Class.
* @author Claus Polanka
*/
public class TestActorManager extends TestCase {

private ActorManager am;
private EntityManager em;
private EntityManagerFactory emf;

private static final ActorGenEntity TESTACTOR1 = new ActorGenEntity(1, "Claus", "Polanka");
private static final ActorGenEntity TESTACTOR2 = new ActorGenEntity(2, "Barbara", "Ebinger");
private static final ActorGenEntity TESTACTOR3 = new ActorGenEntity(3, "Irene", "Polanka");

public TestActorManager(String testName) {
super(testName);
}

@Override
protected void setUp() throws Exception {
emf = Persistence.createEntityManagerFactory("pu-medienverwaltung");
em = emf.createEntityManager();
am = new ActorManager(emf);
}

@Override
protected void tearDown() throws Exception {
am.close();
em.close();
emf.close();
}

public void testCRUD() {
am.createActor(TESTACTOR1);
ActorGenEntity actor = am.findById(1);
assertEquals(actor.getFirstname(), "Claus");

actor.setFirstname("Barbara");
am.updateActor(actor);

actor = am.findById(1);
assertEquals(actor.getFirstname(), "Barbara");

am.createActor(TESTACTOR2);
am.createActor(TESTACTOR3);

List list = am.getAll();
assertEquals(list.size(), 3);

am.removeAll();
list = am.getAll();
assertEquals(list.size(), 0);
}
}

The following picture shows my project-tree and how your project-structure should also look like.

After running your test you should see something like the following.

In the next days I will test more of the JPA features like support for derived Entities and stuff like that.

Cheers

Über sageniuz

https://about.me/ClausPolanka
Dieser Beitrag wurde unter Java, JPA, NetBeans, Tutorials veröffentlicht. Setze ein Lesezeichen auf den Permalink.

10 Antworten zu NetBeans 6.0 | A little JPA Example

  1. Lifo's Blog schreibt:

    Dear, Thank you very much. this is good and helpful post. I need some help. I want to develop a web app with Struts, Hibernate and Spring using NetBeans IDE 6.0. So, please help me by a simple example.

  2. Claus Polanka schreibt:

    Dear, no worries I’d like to post more about JPA but right now I’m really busy and have so much university-stuff going on that I’m not able to post that much. Of course I’ll post about a small Struts-Hibernate-Spring Tutorial but I think it won’t be possible before february. I’m really sorry but you will find a lot of good tutorials on the mentioned technologies‘ websites.Cheers

  3. Anonymous schreibt:

    Dear,Your example is very good!. But when I try execute this code, I get this following error:[TopLink Info]: 2008.03.06 09:46:25.640–ServerSession(3668766)–TopLink, version: Oracle TopLink Essentials – 2.0 (Build b58g-fcs (09/07/2007))Exception Description: Cannot acquire data source [data_source].Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial)Do you know about it?. Thank a million, for your help!Diane.

  4. Anonymous schreibt:

    Hello PolankaIts an awesome post…Just make sure that in the method „remove all“ActorGenEntity g =(ActorGenEntity) it.next();I think you have missed out the type casting!!!Its a great post.. It helped me a lot in learning the JPA..

  5. Anonymous schreibt:

    It is extremely interesting for me to read the post. Thank you for it. I like such themes and anything connected to them. I definitely want to read more soon.

  6. Anonymous schreibt:

    Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!

  7. Anonymous schreibt:

    Rather interesting site you've got here. Thanx for it. I like such themes and everything that is connected to this matter. BTW, try to add some photos🙂.

  8. Anonymous schreibt:

    Guten Tag! My name is David Bly . no fax payday loan

  9. Anonymous schreibt:

    I like use viagra, but this no good in my life, so viagra no good.

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s