Stand-alone Persistence in a Java SE Project

This document takes you through the basics of developing a Java application with stand-alone persistence using Java EE 5 technology. This document uses the NetBeans 5.5 release and the Sun Java System Application Server 9.0, Platform Edition.


Expected duration: 15 minutes


Software Needed for the Tutorial

Before you begin, you need to install the following software on your computer:

  • NetBeans IDE 5.5 (download)
  • Java Standard Development Kit (JDK) version 5.0 or version 6.0 (download)
  • Sun Java System Application Server 9.0, Platform Edition (download)

    Note: While this tutorial assumes that you will have the Sun Java System Application Server installed, you can alternatively follow along by downloading just the Persistence API and using a pre-configured database connection.

Notations Used in the Tutorial

  • ${GLASSFISH_HOME}- The installation directory of Sun Java System Application Server 9.0. On Windows systems, this is usually C:\Sun\AppServer\

Tutorial Exercises

The following topics are covered below:


Setting Up the Java Application Project

The goal of this exercise is to download and open the example Java application project and configure the project's classpath to contain the libraries for Java EE 5 and the Java DB database client.

Opening the Example Project

  1. Download the example project and unzip it to a location on your computer.
  2. In Netbeans, choose File > Open Project (Ctrl-Shift-O), select the AddressBook directory, and click Open Project.
  3. Examine the project in the Projects window. The project contains a GUI front end for the program and a DBHelper.java class that populates the database with some sample data.

Configuring the Classpath

  1. Right-click the project's Libraries node and choose Add JAR/Folder.
  2. Add ${GLASSFISH_HOME}/lib/javaee.jar
  3. Add the driver to your database. If you are using the Java DB database bundled with the Sun Java System Application Server, add ${GLASSFISH_HOME}/javadb/lib/derbyclient.jar to the project's classpath.

Coding the Entity Classes

With Java EE 5 persistence, we use a persistence.xml file to define connection settings to the database. We then create entity classes that represent each of the tables in the database, and use getter and setter classes in the entity classes to work with the table data.

Creating a Persistence Unit

  1. Right-click the project and choose New > File/Folder.
  2. From the Persistence category, select Persistence Unit and click Next.
  3. Select the database connection to your application from the drop-down list. (If you are using the Java DB database, this will be: jdbc:derby://localhost:1527/sample[app on APP].) Then, for Table Generation Strategy, select Drop and Create to allow tables to be created at runtime. Leave the rest of the values at their defaults.

  4. Click Finish. The IDE creates persistence.xml and opens it in the Source Editor.
  5. In persistence.xml, switch to the XML View by clicking on the XML button in the upper left corner of the Source Editor (alternatively use Alt+Shift+Right or Alt+Shift+Left). Make sure that the appropriate password for your database connection is supplied. If you are using the JavaDB, the default password is app: <property name="toplink.jdbc.password" value="app"/>

Creating the Address Entity Class

We will now create the Address entity class. When you create the entity class, the IDE adds the @Entity annotation to define the class as an entity class. After we create the class, we will create fields in the class to represent the data that we want in our table.

  1. Right-click the project and choose New > File/Folder.
  2. From the Persistence category, select Entity Class and click Next.
  3. Type Address for the class name, addressbook for the package, and leave the primary key type as Long. Click Finish.

    When you click Finish, the entity class Address.java opens in the Source Editor. In the Source Editor, do the following:
  4. Add the following field declarations to the class: String street; String city; String country;
  5. Choose Refactor > Encapsulate Fields from the right-click menu in the Source Editor. This will allow you to switch the access mode for the fields to private, as well as generate getters and setters for each of the fields. Leave Fields' Visibility at private, and Accessors' Visibility at public. Make sure that getter and setter checkboxes are selected for all fields. Click Next.
  6. In the Refactoring tab of the Output window, click Do Refactoring. The IDE adds the getter and setter methods for the fields and changes the visibility of the fields to private.
  7. We now want to change the name of one of the columns that will be created in our database table: instead of id, we want our column to be called AddressID. To do this, we can use annotations to specify the name of the generated column by adding the following annotation to the id field declaration. Add the following line to the id field declaration in Address.java: @Column(name="AddressID")
  8. Press Alt-Shift-F to generate an import into the class for javax.persistence.Column.

    Your field declaration should now look like this:

Creating the Person Entity Class

We will now create the entity class Person representing the PERSON table in our database.

  1. Right-click the project and choose New > Entity Class.
  2. Type Person for the class name, addressbook for the package, and leave the primary key type as Long. Click Finish.
  3. Create the following field declarations: String surname; String name; Address address;
  4. Choose Refactor > Encapsulate fields to switch the access mode for the fields to private and generate getter and setter for the fields. Again, leave Fields' Visibility at private and Accessors' Visibility at public. Make sure that getter and setter checkboxes are selected for all fields. Click Next.
  5. In the Refactoring tab of the Output window, click Do Refactoring. The IDE adds the getter and setter methods for the fields and changes the visibility of the fields to private.
  6. Add the following annotation (in bold) above the id field declaration: @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="PersonID") private Long id;
  7. Add the following annotation (in bold) above the address field declaration. If you place the cursor in the field declaration you can use the source editor hints to generate the annotation for you: @OneToOne(cascade=CascadeType.ALL) private Address address;
  8. Change the body of the toString method as follows: public String toString() { return surname + ", " + name + ": " + address.getStreet() + ", " + address.getCity() + ", " + address.getCountry(); }
  9. Press Alt-Shift-F to generate any missing import statements.

Editing the DBHelper Class

The DBHelper class is used by the program to interact between the database and the front-end user interface. The class already has a createPersons method that provides data for the database. We need to create methods that enable us to populate the database, insert a new person, and get all entries.

  1. Double-click DBHelper to open it in the Source Editor.
  2. Right-click in the Source Editor and choose Persistence > Use Entity Manager.

    The IDE adds the following field to the class: private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("AddressBookPU");

    and adds the following persist method:

    public void persist(Object object) { javax.persistence.EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); try { // TODO: // em.persist(object); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } finally { em.close(); } }

    The following import statement is also added to the class:

    import javax.persistence.Persistence;
  3. We need to change the name of the persist method created by the Entity Manager so that it corresponds to the add method used elsewhere in our project. Make the following changes (in bold) to the persist method that was just created: public static void add(Object object) { javax.persistence.EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); try { em.merge(object); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } finally { em.close(); } }
  4. Now, add the following methods to the class: public static void setUpDB() { for (Person p: createPersons()) { add(p); } } public static List getData() { return emf.createEntityManager().createQuery("SELECT p FROM Person p").getResultList(); } private static EntityManagerFactory emF = Persistence.createEntityManagerFactory("persistence"); private static EntityManager em = emF.createEntityManager();
  5. Create the following methods in the class: public static void setUpDB() { EntityTransaction et = em.getTransaction(); et.begin(); for (Person p: createPersons()) { em.persist(p); } et.commit(); } public static void add(Object o) { EntityTransaction et = em.getTransaction(); et.begin(); em.persist(o); et.commit(); } -->

Summary

In this exercise, you created a persistence unit and added several entity classes enabling the database to interact with the front-end user interface. You then configured the persistence unit to create tables at deploy time.


Running the Project

Now let's start the database server, build the project, and run the GUI interface.

  1. Start your database server. If you are using the Java DB database, choose Tools > Java DB Database > Start Java DB Server.
  2. Right-click the project node and choose Run Project. The following form displays all of the data in the table:

  3. Choose Menu > Add Person to add a person to the database. Fill in some sample data, as shown below, then click Add.

    The data is added to your database, and you will notice the changes are updated immediately in the Address Book window.

Summary

In this exercise, you set the necessary runtime options and tested the program by displaying the data in the table and adding a new entry.




Next Steps

To send comments and suggestions or get support, please use the feedback link above. To keep informed on the latest developments on the NetBeans IDE J2EE development features, join the nbusers@netbeans.org mailing list.

Posted by 나비:D
:

BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Total :
Today : Yesterday :