CRUD Operations using JPA

I will show how to perform four basic functions, create, read, update and delete (CRUD) on relational database application by using JPA in this post.

I only include two programs in the following. Full source codes can be cloned from https://github.com/henry416/jpatest.
1) Student.java: to define a new entity class;
2) StudentTest.java: to perform CRUD operations;

1. Entity Class: Student.java

package henry416.domain;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Student {
	@Id
	private int id;

	private String name;
	
	private double gpa;
	
	public Student() {}

	public Student(int id) {
		this.id = id;
	}
	
	public Student(int id, String name, double gpa) {
		this.id = id;
		this.name = name;
		this.gpa = gpa;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public double getGpa() {
		return gpa;
	}
	
	public void setGpa(double gpa) {
		this.gpa = gpa;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", gpa="
				+ gpa + "]";
	}

}

2. CRUD Operations: StudentTest.java

package henry416.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import henry416.domain.Student;

public class StudentTest {

	private EntityManager manager;

	public StudentTest(EntityManager manager) {
		this.manager = manager;
	}
 
	public static void main(String[] args) {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
		EntityManager manager = factory.createEntityManager();
		StudentTest test = new StudentTest(manager);

		EntityTransaction tx = manager.getTransaction();
		System.out.println("1. create student records");
		tx.begin();
		try {
			test.createStudents();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();

		System.out.println("2. read student records");
		test.readStudents();

		System.out.println("3. update a student record");
		tx.begin();
		try {
			test.updateStudent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();		

		System.out.println("4. delete a student record");
		tx.begin();
		try {
			test.deleteStudent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();		
		
		System.out.println("5. delete all student records");
		tx.begin();
		try {
			test.deleteStudents();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();		
		
		System.out.println("=> done");
	}

	private void createStudents() {
		// insert a few records
		manager.persist(new Student(1,"Jack Jackson",3.28));
		manager.persist(new Student(2,"Tom Thomson",3.56));
		manager.persist(new Student(3,"Dave Davison",3.65));
		manager.persist(new Student(4,"Neil Nelson",3.56));
		manager.persist(new Student(5,"Mark Markson",3.78));		
	}

	private void readStudents() {
		List<Student> resultList = manager.createQuery("Select s From Student s order by s.id", Student.class).getResultList();
		System.out.println("num of students:" + resultList.size());
		for (Student next : resultList) {
			System.out.println("=> " + next);
		}
	}

	private void updateStudent() {
		// update a student record
		Student stu = manager.find(Student.class, 2);
        	if (stu != null) {
                  System.out.println("from => "+stu);  
        	  stu.setName("Thomas Thomson");
                  stu.setGpa(3.99);
                  System.out.println("to => "+stu);
        	}
	}
	
	private void deleteStudent() {
		// delete ONE record
		Student stu = manager.find(Student.class, 2);
		System.out.println("remove=> "+stu);
		if (stu != null) {
		   manager.remove(stu);
		}

	}
	
	private void deleteStudents() {
		// delete all records
		int deletedCount = manager.createQuery("DELETE FROM Student").executeUpdate();
		System.out.println("total num of records removed => "+deletedCount);
	}
}

3. Result

The following is the execution results:

1. create student records
2. read student records
num of students:5
=> Student [id=1, name=Jack Jackson, gpa=3.28]
=> Student [id=2, name=Tom Thomson, gpa=3.56]
=> Student [id=3, name=Dave Davison, gpa=3.65]
=> Student [id=4, name=Neil Nelson, gpa=3.56]
=> Student [id=5, name=Mark Markson, gpa=3.78]
3. update a student record
from => Student [id=2, name=Tom Thomson, gpa=3.56]
to => Student [id=2, name=Thomas Thomson, gpa=3.99]
4. delete a student record
remove=> Student [id=2, name=Thomas Thomson, gpa=3.99]
5. delete all student records
total num of records removed => 4
=> done

Using JPA to build a J2EE 3-tier Web Application

The purpose of this entry is to demonstrate a full J2EE web application. The application will generate:

    1. a Java Persistence API (JPA) entity modeled on an existing database table
    2. an Enterprise JavaBean (EJB) which will query the database through the JPA
    3. a Servlet coupled with a JavaServer Faces (JSF) 2 framework for information display
    4. a Representational State Transfer (REST) resource capable of providing the JPA entities as web resources

The project will be built in Netbeans 7.2.1 and hosted on Glassfish 3.2.1

Start off by creating a Web Application project and specify the Glassfish Server. Then, clicking on the project, create a new Entity Class from Database (under Persistence) and specify the datasource along with the required tables. Specify a package. Check the NamedQuery, JAXB and Persistence Unit boxes.

Image

Next, create a new stateless EJB in the package (with the annotation @Stateless). We will be using JPA entities as RESTful resources, so tell netbeans to register all REST resources to the javax.ws.rs.Application class automatically and add a Jersey Library (JAX-RS implementation).

@javax.inject.Named
@Path("/customers")
@Stateless
public class CustomerSessionBean {

    @PersistenceContext
    EntityManager em;

    public List<Customer> getCustomers() {
        return (List<Customer>)em.createNamedQuery("Customer.findAll").getResultList();
    }

    //RESTful resource, access at http://localhost:8080/JavaEE6SampleApp/webresources/customers/customer/1
    @GET
    @Path("/customer/{id}")
    @Produces("application/xml")
    public Customer getCustomer(@PathParam("id")Integer id) {
        return
        (Customer)em.createNamedQuery("Customer.findByCustomerId")
        .setParameter("customerId", id).getSingleResult();
    }
}

Next, create the servlet that uses the EJB.

@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {

    @EJB CustomerSessionBean ejb;

    // Access at http://localhost:8080/JavaEE6SampleApp/TestServlet
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet TestServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet TestServlet at " + request.getContextPath () + "</h1>");
            out.println(ejb.getCustomers());
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // HTTPServlet Methods go here
}

Next, we will go about creating the Context and Dependency Injection (CDI) which allows the EJB to support the JSF pages. Create a beans.xml file in the project and set the project framework to JSF. Create a Facelets Template (JSF) in the WEB-INF folder using one of the CSS layouts. Edit it to become:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link href="./../resources/css/default.css" rel="stylesheet" type="text/css" />
        <link href="./../resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
        <title>Facelets Template</title>
    </h:head>
    <h:body>
        <div id="top">
            <ui:insert name="top"><h1>Java EE 6 Sample App</h1></ui:insert>
        </div>

        <div id="content" class="center_content">
            <ui:insert name="content">Content</ui:insert>
        </div>

        <div id="bottom">
            <ui:insert name="bottom"><center>DEMO!</center></ui:insert>
        </div>
    </h:body>
</html>

Delete the old index.xhtml file and replace it with a new Facelets Template Client copy. In this case, the root tag used is :

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
                template="./WEB-INF/template.xhtml"
                xmlns:h="http://java.sun.com/jsf/html">
    <ui:define name="content">
        <h:dataTable value="#{customerSessionBean.customers}" var="c">
            <h:column>#{c.name}</h:column>
            <h:column>#{c.customerId}</h:column>
        </h:dataTable>
    </ui:define>
</ui:composition>

And we are done. The final results are:

Screenshot from 2013-01-07 12:34:30 Screenshot from 2013-01-07 12:34:43 Screenshot from 2013-01-07 12:34:53 Screenshot from 2013-01-07 12:35:17

A simple java program to simulate a stopwatch

Recently, I wrote a small java program to simulate a stopwatch count down by using java.util.Timer class method scheduleAtFixedRate(TimerTask task, long delay, long period) which schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.

My program just simply count down from 1000 to 1 second by second roughly.

//Stopwatch

import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
  static int interval;
  static Timer timer;

  public static void main(String[] args) {

    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval =10000;
    timer.scheduleAtFixedRate(new TimerTask() {
      public void run() {
         System.out.println(setInterval());
      }
    }, delay, period);
  }

  private static final int setInterval(){
    if( interval== 1) timer.cancel();
      return --interval;
  }
}

Blackberry Development 1: setup environment

Assumption: Windows XP SP3 onward and Blackberry Desktop Software (from the CD with your phone or installed from RIM website)

1. Download and Install

1.1. Java SE JDK

Install it from www.oracle.com/technetwork/java/index.html if not installed.

1.2. Eclipse and BlackBerry JDE Plug-in for Eclipse

There are two BlackBerry development environments produced by RIM: the BlackBerry Java Development Environment (JDE) and the BlackBerry JDE Plug-in for Eclipse.

To use Eclipse to develop for BlackBerry, you’ll need to download Eclipse IDE. However, to make things simple for you, RIM has bundled Eclipse 3.6 (Helios) with the BlackBerry JDE Plug-in with BlackBerry SDK 7.0. You can download the BlackBerry Java Plug-in for Eclipse at http://us.blackberry.com/developers/javaappdev/devtools.jsp.

I already have Eclipse installed, and the following steps are used to download and install the Blackberry Plug-In onto Eclipse:

  • Select Help Menu.
  • From the menu, select the Install New Software menu item. The Install New Software screen will appear.
  • From the Install New Software screen, click the Add button.
  • Paste http://www.blackberry.com/go/eclipseUpdate/3.6/java into the location text box, give it the name “text box,” and click OK .
  • Select the BlackBerry Java Plug-in item and at least one BlackBerry Component Pack item that you want to work.
  • Then follow the onscreen instruction to finish installation. You will have to restart Eclipse IDE in order for the installation to take effect.
1.3. Additional Simulators

In addition to the simulators that are available to you in the BlackBerry Java Plug-in for Eclipse, RIM provides many simulators that are very useful for testing how your application functions with different screen resolutions or input methods. The simulators can be downloaded from the Developer Zone, at http://na.blackberry.com/eng/developers/resources/simulators.jsp

1.4. Code Signing Key

Please register for the code signing keys at http://na.blackberry.com/eng/developers/javaappdev/codekeys.jsp.

The online application form for signing keys is available at https://www.blackberry.com/SignedKeys/

To install your code signing keys in Eclipse with the BlackBerry JDE plug-in, simply import the keys by doing the following:

  • From Eclipse IDE, select Windows from the menu, and then choose Open Perspective Image from book Others.

  • Select the BlackBerry Application Development perspective.
  • Then from the menu, select BlackBerry Image from book Sign Image from book Install New Key. You’ll be prompted to create a new public/private key pair.
  • Click Yes on this dialog, and you’ll be asked for a private key password to protect your key file. Remember this password—you’ll be asked for it every time you want to sign your application. You’ll then be asked to generate some random data by moving your mouse pointer around to increase the radomized calculation.
  • After this, you’ll be asked to enter the PIN you provided when you applied for your keys and the private key password you just entered.
  • For the next two keys, you’ll already have generated your key pair, so you’ll just have to enter the PIN and private key password.

    Once you’ve created your key pair and installed your three keys, the key information is stored in three files:

         sigtool.csk
         sigtool.db
         sigtool.set

    The location of these files is <eclipse_directory>\plugins\net.rim.ejde\vmTools\, where <eclipse_directory> is where you installed your Eclipse environment (i.e., C:\Eclipse\plugins\net.rim.ejde\vmTools\).

    It’s also a very good idea to keep a backup of these files and your original key files if you ever have to rebuild your development environment

From now on, the development environment is ready.

Query Database Using Swing UI

SimpleForm.java

Query DB on A Swing Form

DoConnect(): connect to db, run query, get first record into UI

BtnAction(): logic to manipulate the records (NEXT, PRVIOUS, FIRST, LAST)

Rest of codes (SWING UI) are generated by using NeatBean IDE 6.8 on Linux.

/*
 to compile: javac -cp /usr/share/java/postgresql.jar SimpleForm.java
 to execute: java -cp /usr/share/java/postgresql.jar:. SimpleForm
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;

public class SimpleForm extends javax.swing.JFrame {
    Connection con;
    Statement stmt;
    ResultSet rs;

    /** Creates new form SimpleForm */
    public SimpleForm() {
        initComponents();
        DoConnect();
    }

    public void DoConnect( ) {
        try {
            //connect to the database
            con = DriverManager.getConnection("jdbc:postgresql:mydb",
                    "testuser","testpassword");
            // construct a sql statement, execute it and load resultset to rs                                    "logan","ready2go");
            //stmt = con.createStatement();
            stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
            String sql = "select firstname, lastname, name from employees, departments where employees.department = departments.id";
            rs = stmt.executeQuery(sql);
            // retrieve the fields from rs to txtFields
            if (rs.next()) {
               txtFirst.setText(rs.getString("firstname"));
               txtLast.setText(rs.getString("lastname"));
               txtDept.setText(rs.getString("name"));
            }
            else { JOptionPane.showMessageDialog(SimpleForm.this, "No records!");}
        }
        catch (SQLException err) {
            JOptionPane.showMessageDialog(SimpleForm.this, err.getMessage());
        }
    }
    // Next, Previous, First, Last Action Event Handlers
    public void DoBtnAction(int BtnAction ) {
    try {
         if (rs != null)
         {
          boolean Action = false;
          switch (BtnAction) {
            case 1:  Action = rs.next();
                     break;
            case 2:  Action = rs.previous();
                     break;
            case 3:  Action = rs.first();
                     break;
            case 4:  Action = rs.last();
                     break;
            default:
                     break;
            }
          if ( Action ) {
            txtFirst.setText(rs.getString("firstname"));
            txtLast.setText(rs.getString("lastname"));
            txtDept.setText(rs.getString("name"));
                        }
          else {
          switch (BtnAction) {
            case 1:  rs.previous( );
                     JOptionPane.showMessageDialog(SimpleForm.this, "End of File");
                     break;
            case 2:  rs.next( );
                     JOptionPane.showMessageDialog(SimpleForm.this, "Start of File");
                     break;
            default:
                     break;
                             }
              } // end of else for Action
             } // if Action
         else { JOptionPane.showMessageDialog(SimpleForm.this, "No records!");}
        } // try
    catch (SQLException err) {
            JOptionPane.showMessageDialog(SimpleForm.this, err.getMessage());
        }    
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        txtFirst = new javax.swing.JTextField();
        txtLast = new javax.swing.JTextField();
        txtDept = new javax.swing.JTextField();
        lblFirst = new javax.swing.JLabel();
        lblLast = new javax.swing.JLabel();
        lblDept = new javax.swing.JLabel();
        btnNext = new javax.swing.JButton();
        btnPrevious = new javax.swing.JButton();
        btnFirst = new javax.swing.JButton();
        btnLast = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblFirst.setText("First Name:");

        lblLast.setText("Last Name");

        lblDept.setText("Department:");

        btnNext.setText("Next");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnPrevious.setText("Previous");
        btnPrevious.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPreviousActionPerformed(evt);
            }
        });

        btnFirst.setText("First");
        btnFirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFirstActionPerformed(evt);
            }
        });

        btnLast.setText("Last");
        btnLast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLastActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnPrevious)
                        .addGap(18, 18, 18)
                        .addComponent(btnNext)
                        .addGap(46, 46, 46)
                        .addComponent(btnFirst)
                        .addGap(18, 18, 18)
                        .addComponent(btnLast)
                        .addContainerGap())
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(lblDept)
                            .addContainerGap())
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(txtDept, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(txtFirst, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblFirst))
                                    .addGap(42, 42, 42)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(lblLast)
                                        .addComponent(txtLast, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addContainerGap(81, Short.MAX_VALUE)))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFirst)
                    .addComponent(lblLast))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtLast, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFirst, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addComponent(lblDept)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtDept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPrevious)
                    .addComponent(btnLast)
                    .addComponent(btnFirst)
                    .addComponent(btnNext))
                .addContainerGap(58, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {
        DoBtnAction(1);
    }

    private void btnPreviousActionPerformed(java.awt.event.ActionEvent evt) {
        DoBtnAction(2);
    }

    private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {
        DoBtnAction(3);
    }

    private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {
        DoBtnAction(4);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SimpleForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btnFirst;
    private javax.swing.JButton btnLast;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JLabel lblDept;
    private javax.swing.JLabel lblFirst;
    private javax.swing.JLabel lblLast;
    private javax.swing.JTextField txtDept;
    private javax.swing.JTextField txtFirst;
    private javax.swing.JTextField txtLast;
    // End of variables declaration

}

How to bind data to JavaFX Form

SimpleFormFx.java

/*
 * File: SimpleFormFx.java
 *    Create a SimpleForm from a query
 * Author: https://henry416.wordpress.com/
 *
 * Compile: javac -cp "C:\Program Files\Oracle\JavaFX Runtime 2.0\lib\jfxrt.jar" SimpleFormFx.java
 * Execute: java -cp "C:\Program Files\Oracle\JavaFX Runtime 2.0\lib\jfxrt.jar";"Z:\test\javafx\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar";. SimpleFormFx
 * ------------------------------
 * Test Data:
 * mysql -u testuser -p
 * mysql> select * from test.t1;
   +------+------------+
   | name | telephone  |
   +------+------------+
   | John | 4168889999 |
   | Tom  | 4161239999 |
   +------+------------+
   2 rows in set (0.00 sec)
 *--------------------------------
 */
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.geometry.Insets;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class SimpleFormFx extends Application {

   @Override
   public void start(Stage stage) {
    Group root = new Group();
    Scene scene = new Scene(root,300,200,Color.WHITE);
        Connection con;
        Statement stmt;
        ResultSet rs;
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.setSpacing(10);
        // create a title, add it into vbox
        Text title = new Text("Simple Database Form in JavaFX");
        title.setFont(Font.font("Amble CN", FontWeight.BOLD, 12));
        vbox.getChildren().add(title);

        try {
            //connect to the database
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/","testuser","testpassword");
            // construct a sql statement, execute it and load resultset to rs
            stmt = con.createStatement();
            String sql = "select name,telephone from test.t1";
            rs = stmt.executeQuery(sql);

            if (rs != null) {
            // more controls in an array, add them into vbox
            ResultSetMetaData rsMetaData = rs.getMetaData();
            int numberOfColumns = rsMetaData.getColumnCount();
            rs.next();
            // get the column names into labels, fields into textfields, pack them into vbox
            for (int i = 1; i < numberOfColumns + 1; i++) {
              Label lbl= new Label(rsMetaData.getColumnName(i)+":");
              TextField txtField = new TextField(rs.getString(i));
              HBox hbox =new HBox(5);
              hbox.getChildren().addAll(lbl,txtField);
              vbox.getChildren().add(hbox);
            }
            }
        }
        catch (SQLException err) {
            System.err.println (err.getMessage());
        }

       // put VBox onto a border Pane
       BorderPane border = new BorderPane();
       border.setLeft(vbox);
       // add the border pane as a child
       root.getChildren().add(border);

       stage.setTitle("Simple Database Form in JavaFX");
       stage.setScene(scene);
       stage.show();
   }

   public static void main(String[] args) {
       launch(args);
   }
}
 

How to bind data from database with Java Swing UI

I have the following data in a PostgreSQL database called ‘mydb’ on Linux.

~$ psql mydb
psql (8.4.9)
Type "help" for help.

mydb=# select * from employees;
 id |   lastname   | firstname | department
----+--------------+-----------+------------
  1 | Werner       | Max       |          1
  2 | Lehmann      | Daniel    |          2
  3 | Roetzel      | David     |          1
  4 | Scherfgen    | David     |          2
  5 | Kupfer       | Andreas   |          2
  6 | Scheidweiler | Najda     |          2
  7 | Jueppner     | Daniela   |          4
  8 | Hasse        | Peter     |          4
  9 | Siebigteroth | Jennifer  |          3
(9 rows)

mydb=# select * from departments;
 id |    name    
----+------------
  1 | Management
  2 | R&D
  3 | Marketing
  4 | Accounting
(4 rows)

mydb=# select firstname, lastname, name
mydb-# from employees, departments
mydb-# where employees.department = departments.id;
 firstname |   lastname   |    name    
-----------+--------------+------------
 David     | Roetzel      | Management
 Max       | Werner       | Management
 Najda     | Scheidweiler | R&D
 Andreas   | Kupfer       | R&D
 David     | Scherfgen    | R&D
 Daniel    | Lehmann      | R&D
 Jennifer  | Siebigteroth | Marketing
 Peter     | Hasse        | Accounting
 Daniela   | Jueppner     | Accounting
(9 rows)

mydb=#

The following is the Java program which consists of two parts: the bottom part  (initComponents()) is the UI generated by using the Netbean IDE, and the upper part is the java program (DoConnect() ) to connect to a database mydb in PostgreSQL, and run a query, and then bind the data (first record) to the text fields on the UI.  (Basically, it should work with all the JDBC compliance DB like mysql, derby, Oracle, Sybase, UDB or Microsoft SQL. Just replace the connection string, and put the relevant JDBC driver jar file in the classpath. Also, the compile and execute command are for Linux.)

SimpleForm (Data Binding Using Java Swing)
SimpleForm (Data Binding Using Java Swing)
SimpleForm.java 
/*
 Written by: https://henry416.wordpress.com/
 to compile: javac -cp /usr/share/java/postgresql.jar SimpleForm.java
 to execute: java -cp /usr/share/java/postgresql.jar:. SimpleForm
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class SimpleForm extends javax.swing.JFrame {
    Connection con;
    Statement stmt;
    ResultSet rs;
    /** Creates new form SimpleForm */
    public SimpleForm() {
        initComponents();
        DoConnect();
    }
    public void DoConnect( ) {
        try {
            //connect to the database
            con = DriverManager.getConnection("jdbc:postgresql:mydb","testuser","testpassword");
            // construct a sql statement, execute it and load resultset to rs
            stmt = con.createStatement();
            String sql = "select firstname, lastname, name from employees, departments where employees.department = departments.id";
            rs = stmt.executeQuery(sql);
            // retrieve the fields from rs to txtFields
   rs.next();
            txtFirst.setText(rs.getString("firstname"));
            txtLast.setText(rs.getString("lastname"));
            txtDept.setText(rs.getString("name"));
        }
        catch (SQLException err) {
            JOptionPane.showMessageDialog(SimpleForm.this, err.getMessage());
        }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SimpleForm().setVisible(true);
            }
        });
    }
 /*
  The following is GUI generated from Netbean
 */
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        txtFirst = new javax.swing.JTextField();
        txtLast = new javax.swing.JTextField();
        txtDept = new javax.swing.JTextField();
        lblFirst = new javax.swing.JLabel();
        lblLast = new javax.swing.JLabel();
        lblDept = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        lblFirst.setText("First Name:");
        lblLast.setText("Last Name");
        lblDept.setText("Department:");
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblDept)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtDept, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtFirst, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblFirst))
                                .addGap(42, 42, 42)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblLast)
                                    .addComponent(txtLast, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(81, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFirst)
                    .addComponent(lblLast))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtLast, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFirst, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addComponent(lblDept)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtDept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(120, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>

    // Variables declaration - do not modify
    private javax.swing.JLabel lblDept;
    private javax.swing.JLabel lblFirst;
    private javax.swing.JLabel lblLast;
    private javax.swing.JTextField txtDept;
    private javax.swing.JTextField txtFirst;
    private javax.swing.JTextField txtLast;
    // End of variables declaration
}