站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题Implementing Stand-alone Persistence in a Java SE Project Using NetBeans IDE 5.5

Implementing Stand-alone Persistence in a Java SE Project Using NetBeans IDE 5.5

摘要: 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.

Software Needed for the Tutorial

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

Notations Used in the Tutorial

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 for your application from the drop-down list. (If you are using the Java DB database and the sample database, the connection will be: jdbc:derby://localhost:1527/sample[app on APP]. If you do not have the sample database, you can create a new database and then specify the new database in the persistence unit. The sample database is created when you register the Sun Java System Application Server with the IDE.)
  4. Select Drop and Create as the Table Generation Strategy. When this is selected the tables are created at runtime. Leave the rest of the values at their defaults.
    image of New Persistence Unit Wizard
  5. Click Finish. The IDE creates persistence.xml and opens it in the Source Editor.
  6. 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.
  4. Add the following field declarations to Address.java:
        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")
    Your field declaration should now look like this:
    image of id field declaration in Source Editor
  8. Press Alt-Shift-F to generate an import into the class for javax.persistence.Column.

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 help 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();
    }

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:
    image of address form window displaying list of addresses
  3. Choose Menu > Add Person to add a person to the database. Fill in some sample data, as shown below, then click Add.

    image of form window for entering a new addresses

    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 mailing list.


↑返回目录
前一篇: Introduction to the JSF Framework
后一篇: GUI Design with NetBeans Mobility Pack for CDC