JPA and Database Access

This post converts the application example from File Input/Ouput to write to and read from a database using the Java Persistence API (JPA) and the ObjectDB object-oriented database management system (ODBMS) with NetBeans and Glassfish.

ObjectDB provides built-in support for the JPA and Java Data Objects (JDO) APIs, which are standard Java object database APIs. With ObjectDB, you can write database code using Java classes and objects and dispense with database drivers, tables, mapping, records, and more.

The window on the left below appears when you start the Dba application, and the window to its right appears when you click the Click Me button. At this point,  whatever is entered into the text field is saved to the database table. Then, the data is retrieved from the database and displayed in the window as shown.

DB1 DB2

This example was created with the following software:

  • Java EE SDK 7u1-web (Glassfish 4)
  • NetBeans IDE 8.0.2
  • ObjectDB 2.5.0_06

Build in Eclipse

  1. Set Up Project for ObjectDB
  2. Create a JPA Entity Class
  3. Add the Main Class
  4. Enable JavaFX
  5. Add Cascading Style Sheet
  6. Run the Program

1. Set Up Project for ObjectDB

  1. Go to http://www.objectdb.com/object/db/database/download and download and extract the ObjectDB files.
  2. In Eclipse, select File > New > Project > Java Project.
  3. In the New Java Project dialog, name the project JPAProject and click Next.
  4. In the Libraries tab, select Add External JARs… and select the objectdb.jar file from the bin subdirectory of the ObjectDB installation directory.
  5. Click Finish.

2. Create a JPA Entity Class

  1. Right-click JPAProject and select New > Class.
  2. Name the package jpaproject and the main class JPAEntity.
  3. Click Finish.
  4. Copy the following code into the JPAEntity class and save.

JPAEntity class:

The example application data is contained in an entity class. An entity is a lightweight persistence domain object. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table.

In this example, think of a table called DBAEntity with rows of text. Each time the user enters text and clicks the Click Me button, a new row with the entered text is added to the table.

A JPA entity class is a basic Java class that includes the @Entity notation and implements the Serializable interface. The required @ID notation indicates the field to be the primary key for the database table. The optional @GeneratedValue notation indicates how JPA generates the primary key. In this example, JPA auto-generates the primary key values.

A JPA entity class must have a no-argument constructor that JPA uses when it retrieves data from the database. The no-argument constructor is not used by the application.

package jpaproject;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class JPAEntity implements Serializable{
  /**
     * 
     */
    private static final long serialVersionUID = 1L;
@Id 
  @GeneratedValue(strategy=GenerationType.AUTO) 
  private int id;
  private String text;

  public JPAEntity() {/*No argument constructor for JPA to use*/}

  JPAEntity(String text) {
    this.text = text;
  }
}

3. Add the Main Class

  1. Right-click JPAProject and select New > Class
  2. In the New Class dialog, name the class Main.
  3. Copy the following code into the class file and save.

Main class file:

package jpaproject;

import java.util.Iterator;
import java.util.List;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javax.persistence.*;
import javax.persistence.Query;
import static javafx.application.Application.launch;

public class Main extends Application {
  TextField textField;
  Label text, clicked;
  Button button, clickButton;
  BorderPane BPane;
  private boolean _clickMeMode = true;
  @Override
  public void start (Stage primaryStage) {    
    //Create GridPane
    BPane = new BorderPane();
    BPane.setId("grid-pane");
    BPane.getStyleClass().add("pane-styles");

    //Create Scene and add Grid
    Scene Scene = new Scene(BPane, 300, 200);
    Scene.getStylesheets().add(this.getClass().getResource(
                    "jpaproject.css").toExternalForm());
    //Create the stage and add the scene
    primaryStage.setTitle("Database IO Application");
    primaryStage.setScene(Scene);
        
    text = new Label("Text to save to database:");
    textField = new TextField();
    textField.setMaxWidth(200);
    button = new Button("Click Me");
    button.setOnAction((ActionEvent event) -> {
      String entity = null;
      // Open a database connection
      // Create a new database if it doesn't exist yet:
         EntityManagerFactory emf =
         Persistence.createEntityManagerFactory("$objectdb/db/JPAEntity.odb");
         EntityManager em = emf.createEntityManager();
         //Variable to display text read from file
         if (_clickMeMode) {
           try {
             //Get text from UI
             String text1 = textField.getText();
             //Write to database:
             //Create entity class and intialize it with data
             JPAEntity jpaEntity = new JPAEntity(text1);
             //Start a transaction
             em.getTransaction().begin();
             //Write data to the database
             em.persist(jpaEntity);
             //End the transaction
             em.getTransaction().commit();
             //Clear text field
             textField.setText("");
             //Code to read all entries from the database
             em.getTransaction().begin();
             Query query = em.createQuery("SELECT text FROM JPAEntity jpaEntity");
             List list = query.getResultList();
             Iterator iterator = list.iterator();
             while (iterator.hasNext()) {
               entity = (String)iterator.next();
             }
             em.getTransaction().commit();
           } catch (com.objectdb.o._PersistenceException e) {
             System.out.println(e);
           } finally {
             try {
               em.close();
             } catch (java.lang.Exception e) {
               System.out.println(e);
           }
         }
         //Display text read from file
         text.setText("Text retrieved from database: \n\n" + entity);
         BPane.getChildren().remove(textField);
         button.setText("Click Again");
         _clickMeMode = false;
       } else {
         //Save text to database
         text.setText("Text to save to database:");
         BPane.getChildren().add(textField);
         textField.setText("");
         button.setText("Click Me");
         _clickMeMode = true;
       }
     });
    //Set positions for each control in the BorderPane
    BPane.setTop(text); 
    BPane.setCenter(textField);
    BPane.setBottom(button);
 
    //Show the scene
    primaryStage.show(); 
  } 
  //main method
  public static void main(String[] args){
    launch(args);
  }
}

4.Enable JavaFX in Eclipse

JavaFX is not by default enabled on Eclipse. The easiest way to enable JavaFX is to add the path to jfxrt.jar to your build path.

  1. Right click  JPAProject.
  2. In the drop-down menu, select Build Path > Configure Build Path.
  3. In the Libraries tab, select Add External JARs.
  4. Add the path to your jfxrt.jar file, for example:
    C:\Program Files (x86)\Java\jre1.8.0_91\lib\ext.javafxconfigure

Alternately and especially if you plan to do a lot of JavaFX programming, you can install e(fx)clipse, which is a plugin for Eclipse that supports JavaFX. See the following link for more information: https://www.eclipse.org/efxclipse/install.html#for-the-lazy.

5. Add Cascading Style Sheet

  1. Right-click the jpaproject package.
  2. Select New > Other > Web > CSS File
  3. Name the Cascading Style Sheet (CSS) jpaproject
  4. Click Finish
  5. Copy the following style definitions into jpaproject:

jpaprogram css:

/* Global style definitions. Apply to all UI elements in the application. */
   .root {
    display: block; 
    -fx-font-size: 14px "Serif"; 
    -fx-font-family: Tahoma;
    -fx-font-weight: NORMAL;
   }

/* Border pane style definitions. Apply to all UI elements in the border pane. 
    The pane-styles style definition was added to the border pane on Line 26. */
    .pane-styles {
        -fx-background-color: rgb(87, 206, 248);
        -fx-hgap: 2px;
        -fx-vgap: 2px;
        -fx-padding: 5px;
        -fx-grid-lines-visible: false; 
    }

/* Labels in the border pane have this additional style definition. */
    .pane-styles .label {
        -fx-padding: 10 10 10 0; 
    }

/* Text fields in the border pane have these additional style     definitions. */
    .pane-styles .text-field {
        -fx-background-color: #999999, #336699,
        linear-gradient(to bottom, #fff 0%, #ccc 100%);
        -fx-background-insets: 1px, 2px, 3px; 
        -background-radius: 0px 0px 9px 0px, 0px 0px 8px 0px, 0px 0px 8px 0px;
        -padding: 5px;
        -fx-display-caret: true;
    }

/* buttons added to the border pane have these additional style definitions. */
    .pane-styles .button { 
        -fx-background-color: #707070,
        linear-gradient(#fcfcfc, #f3f3f3),
        linear-gradient(#f2f2f2 0%, #ebebeb 49%, #dddddd 50%, #cfcfcf 100%); 
        -fx-background-insets: 1px, 2px, 3px;
        -fx-padding: 3px 20px 3px 20px; 
    }

6. Run the Program

  1. Save and close the files
  2. Right-click JPAProject
  3. Select Run As  > Java Application

 

Advertisements
JPA and Database Access

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s