NetBeans JPA and Hibernate Tutorial

This tutorial illustrates the usage of JPA with Hibernate as the persistence layer for a Java SE application. For this tutorial we use a PostgreSQL database. The installation of PostgreSQL and creation of the test database is not handled in this tutorial.

Start NetBeans and create a new Java project.

JPA Tutorial: Screenshot new project wizard

Name your project «JPATutorial» and deselect the «Create Main Class» checkbox. Click on «Finish» and the setup wizard creates your project. Right click the «Source Packages» note in the project explorer and select «New -> Java Package». Name the package «jpatutorial» and click «Finish».

Libraries

We need some additional libraries for our project. First we need the Hibernate Core and Hibernate Entity Manager libraries. You can download this libraries from the Hibernate website. Second, we need the jdbc drivers for our PostgreSQL database system. And last, we need the JPA libraries from the Java EE 5 SDK. You can download this from the Sun website or if you have a installed Sun Java System Application Server, you can simply use the javaee.jar from this installation.

Use the NetBeans Library Manager under «Tools -> Library Manager» to create a new class library. Name the library «Hibernate-JPA» and choose «Class Libraries» as Library type.

Add the following files to the library class path:

from Hibernate Core:
hibernate3.jar
lib/antlr-2.7.6.jar
lib/asm-attrs.jar
lib/asm.jar
lib/c3p0-0.9.1.jar
lib/cglib-2.1.3.jar
lib/commons-collections-2.1.1.jar
lib/commons-logging-1.0.4.jar
lib/concurrent-1.3.2.jar
lib/dom4j-1.6.1.jar
lib/ehcache-1.2.3.jar
lib/javassist.jar
lib/log4j-1.2.11.jar

from Hibernate Entity Manager:
hibernate-entitymanager.jar
lib/hibernate-annotations.jar
lib/hibernate-commons-annotations.jar
lib/jboss-archive-browsing.jar

from Java EE 5 SDK:
javaee.jar

from PostgreSQL JDBC driver:
postgresql-8.2-504.jdbc3.jar

JPA Tutorial: Screenshot library manager

Persistence Unit

Now we create the persistence.xml file, the main configuration file for a JPA application. Right click your project in the project explorer and choose «New -> File/Folder». Select the «Persistence» category and the file type «Persistence Unit». Click next, the wizard asks about the persistence unit name, the persistence library and the database connection. So we want to use Hibernate as our persistence provider and PostgreSQL as database backend, our choices should look like this:

JPA Tutorial: Screenshot persistence unit wizard

If your database connection is not already defined you can use the «New database connection…» wizard to create it.

Leave the setting «Create» for the table generation scheme. This automatically create needed tables in the database. Use «Drop and Create» if your tables should be deleted and newly created on every program start (good for unit tests). «None» is the preffered setting for production environment and does nothing on program start.

We want to make this a swing application. So right click the package and choose «New -> JFrame Form». Type «MainUI» as class name and click finish. The wizard generates our new swing class and starts the matisse gui builder.

Entity class

JPA uses entity classes to persist information. An entity class is a simple pojo with annotations. You should always implement the Serializable interface, although it’s not needed. Background: In an Java EE environment, entity objects are often transfered between an enterprise java bean and a web application. The enterprise bean lives in the ejb container and the web application in the web container. When objects are transfered between containers, they must be serializable.

Right click your «jpatutorial» package and choose «New -> File/Folder». Select «Entity Class» from the «Persistence» category and click next. Enter Address as class name and click finish.

Place the cursor above the constructor and add the following code:

private String customerNo;
private String lastname;
private String firstname;
private String street;
private String postcode;
private String city;

Right click in the editor window and choose «Refactor -> Encapsulate fields…» to create the getter and setter methods for our properties.

User interface

Now we need some gui components for the application. Drag and drop six JLabel and six JTextField components onto the frame.

Name the label components «customerNoLabel», «nameLabel», «firstnameLabel», «streetLabel», «postcodeLabel» and «cityLabel». Set the component text property to a corresponding value.

For the textfield components choose «customerNoText», «nameText», «firstnameText», «streetText», «postcodeText» and «cityText» as component name. Clear the text property of this components.

Drag two JButton components to the page, one named «Load» and the other named «Save». Set the name properties to «loadButton» and «saveButton».

Your frame should look like this:

JPA Tutorial: Screenshot MainUI frame

Store object

Select the Save button, right click and choose «Events -> Action -> actionPerformed». Enter the following code into the event handler:

private void saveButtonActionPerformed(ActionEvent evt) {
  Address address = new Address();
  address.setCustomerNo( customerNoText.getText() );
  address.setLastname( lastnameText.getText() );
  address.setFirstname( firstnameText.getText() );
  address.setStreet( streetText.getText() );
  address.setPostcode( postcodeText.getText() );
  address.setCity( cityText.getText() );

  EntityManagerFactory emf = Persistence.createEntityManagerFactory(
    "JPATutorialPU" );
  EntityManager em = emf.createEntityManager();
  em.getTransaction().begin();

  try {
    em.persist( address );
    em.getTransaction().commit();
  } catch (Exception e) {
    System.out.println( e.getMessage() );
    em.getTransaction().rollback();
  } finally {
    em.close();
  }
}

Right click in your source and select «Fix Imports» (or press ALT-SHIFT-F) to add the needed import statements to your source.

This code creates a Address object and fill it’s properties from our frame. Now we create an EntityManagerFactory for our persistence unit. With this factory we can create the needed EntityManager.

To persist our Address object we use the persist method of the EntityManager.

Retrieve object

Now we want to retrieve an object from the database. Right click the load button and select «Events -> Action -> actionPerformed». Enter the following code into the event handler:

private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           

  EntityManagerFactory emf = Persistence.createEntityManagerFactory(
    "JPATutorialPU" );
  EntityManager em = emf.createEntityManager();
  em.getTransaction().begin();

  String customerNo = JOptionPane.showInputDialog(
    null,
    "Enter customer number",
    "Input",
    JOptionPane.QUESTION_MESSAGE);

  try {
    Query query = em.createQuery(
      "SELECT a FROM Address a WHERE a.customerNo = :customerNo");
    query.setParameter(
      "customerNo",
      customerNo);

    Address address = (Address) query.getSingleResult();

    customerNoText.setText( address.getCustomerNo() );
    lastnameText.setText( address.getLastname() );
    firstnameText.setText( address.getFirstname() );
    streetText.setText( address.getStreet() );
    postcodeText.setText( address.getPostcode() );
    cityText.setText( address.getCity() );

  } catch (Exception e) {
    System.out.println( e.getMessage() );
    em.getTransaction().rollback();
  } finally {
    em.close();
  }
}

Right click in your source and select «Fix Imports» (or press ALT-SHIFT-F) to add the needed import statements to your source. Select «javax.persistence.Query» as fully qualified Name for the Query class.

This code does the following: It asks the user about the customer number, creates a query object and sets the parameter «customerNo» to the entered value. The method «getSingleResult» of the query object returns the result object or an exception if no result was found.

The source code for this tutorial can be downloaded here.

Delphi 7 components

Delphi Library path

$(DELPHI)\Components\Rx\Lib
$(DELPHI)\Components\LotusNotes.bak\lib
$(DELPHI)\Components\SynEdit\Lib
$(DELPHI)\Components\Tbx2k\Lib
$(DELPHI)\Components\ehs\Lib
$(DELPHI)\Components\php4delphi
$(DELPHI)\Components\kalender\lib
$(DELPHI)\Components\InstantObjects\lib
$(DELPHI)\Components\Sysinfo\D7
$(DELPHI)\Components\vnc
C:\Programme\SqlDir\D7
$(DELPHI)\Components\FastReport\LibD7
$(DELPHI)\Components\FastReport252\Lib
$(DELPHI)\Components\PsFr\Lib
$(DELPHI)\Components\winapi\Lib
$(DELPHI)\Components\GLScene\Lib
$(DELPHI)\Components\dunit\src
$(DELPHI)\Components\dunit\Contrib\DUnitWizard\Lib
$(DELPHI)\Components\DxPack\Lib
$(DELPHI)\Components\Cooltray\Lib
$(DELPHI)\Components\Crw\Lib
$(DELPHI)\Components\mxProtector\Lib
$(DELPHI)\Components\Pngimage\lib
$(DELPHI)\Components\mxNativeExcel\Lib
$(DELPHI)\Components\XP Theme Manager\lib
$(DELPHI)\Components\zeosdbo\packages\delphi7\build
$(DELPHI)\Components\FibPlus61\Lib
C:\Progra~1\Borland\jcl\lib\D7
C:\Programme\dxgettext\D7
$(DELPHI)\Source\ToolsAPI
$(DELPHI)\Components\ics\lib
$(DELPHI)\Components\midware\lib
$(DELPHI)\Components\Passcript\Dcu\D7
$(DELPHI)\Components\Passcript\Source
$(DELPHI)\Components\
$(DELPHI)\Components\ubmock\lib
$(DELPHI)\Components\dimime\lib
$(DELPHI)\Components\xmlparser\lib
$(DELPHI)\Components\Formedit
$(DELPHI)\Components\extlib\sources
$(DELPHI)\Components\ScripterStudio\Lib
$(DELPHI)\Components\SQLMemTable\Lib\Delphi7
$(DELPHI)\Components\cipher\source
$(DELPHI)\Components\FastMM\Lib
$(DELPHI)\Components\Orcka\Component Suite\Lib
$(DELPHI)\Components\mxPluginLoader\Lib
$(DELPHI)\Components\Greatis\Gup\Lib
$(DELPHI)\Components\SUIPack\Lib
$(DELPHI)\Components\vclskin\d7
$(DELPHI)\Components\SuiSkin\Source\Delphi7
$(DELPHI)\Components\tb2merge\Lib
$(DELPHI)\Components\dcpcrypt\Lib
$(DELPHI)\Components\sap\lib
$(DELPHI)\Components\bsskin\bsfd7
C:\PROGRA~1\Borland\jcl\source
C:\Programme\Borland\jvcl\common
C:\Programme\Borland\jvcl\lib\D7
(DELPHI)\Components\AsyncPro\Lib
$(DELPHI)\Components\Toolbar2k\lib

Installed components

Cool Tray Icon
DCPcrypt
EC Software Help Suite
Fast Report 2.52
Fast Report 3.0
FIBPlus
GLScene
Greatis Ultimate Pack
Help & Manual Project wizard
InstantObjects
ICS
JCL
JVCL
Max’s Native Excel Component
Max’s Plug-In Component
Max’s Protector Component
MiTeC System Information Component
php4delphi
Pragnaan FastReport Export Filters
RemObjects Pascal Script
RX Library
SQL Direct
Sunisoft SUIPack
Synedit
Toolbar 2000
TBX2k
TMS Component Pack
Tsc Excel Export Pack
TurboPower Async Pro
VclSKin
VNC
XML Parser Components
ZEOS Components

Fill a treeview programmatically

You must build a collection of TreeNode objects and add this collection to the TreeView control. Each TreeNode object has several properties to set up the visual appearance and functionality.

Important TreeNode properties

expanded - Shows this node expaned with children
ext - Title text of the node
target - Target browser window
toolTip - Tooltip text to display
url - Hyperlink to navigate to
action - Name of method to call if user selects this node
actionListenerExpression - Expression for action listener method.

Adding icon to TreeNode

To add a icon to the TreeNode you must first create a ImageComponent. Now you can set the theme specific icon with the setIcon method. Use a constant of class ThemeImages for the icon name. Add the created ImageComponent as facet to the TreeNode.

Sample:

ImageComponent image = new ImageComponent();
image.setIcon( TreeImages.TREE_FOLDER );
treeNode.getFacets().put( treeNode.IMAGE_FACET_KEY, image );

Setting Action Expression for TreeNode

To set the Action Expression of a TreeNode you must use the method setActionExpression of the TreeNode object. This method needs a MethodExpression object as parameter.

Sample code:

ExpressionFactory ef = FacesContext.
  getCurrentInstance().
  getApplication().
  getExpressionFactory();
ELContext elContext = FacesContext.
  getCurrentInstance().
  getELContext();
MethodExpression me = ef.createMethodExpression(
  elContext,
  "#{Page1.treeNode_action}",
  String.class, new Class[]{} );
treeNode.setActionExpression( me );

JAAS with active directory authentication in a web application

This is a sample to use JAAS authentication with a windows active directory server. I use a Sun Java System Application Server, so the steps with other servers could be different.

Step 1: Defining LDAP realm

In this example you must define a LDAP realm named «ads-realm» with the following parameters:

Realm class:

com.sun.enterprise.security.auth.realm.ldap.LDAPReam

Properties:

directory            = ldap://ads.host.name:389
base-dn              = DC=ads,DC=domain,DC=com
search-bind-dn       = user
search-bind-password = password
search-filter        = (&(objectClass=user)(sAMAccountName=%s))
group-search-filter  = (&(objectClass=group)(member=%d))
jaas-context         = ldapRealm

You must change directory, base-dn, search-bind-dn and search-bind-password to your active directory configuration. The «search-bind-dn» and «search-bind-password» parameters are needed, because with default settings active directory doesn’t allow anonymous users to browse the directory.

Step 2: Setting the following JVM Switch for refferals

The following JVM switch is needed with active directory LDAP servers:

-Djava.naming.referral=follow

Add this switch to your server startup script or with the admin console.

Step 3a: Basic authentication

Add the following section to your web.xml or go to Step 3b for form
based authentication.


  BASIC
  ads-realm

Step 3b: Form based authentication

Add the following section to your web.xml:


  FORM
  ads-realm
  
    /login.html
    /login.html
  

Create the page /login.html with a least the following code:


  
  
    
Username:
Password:

Step 4: Adding security role to web.xml

Add at least one security role to your web.xml, in this example «userRole».


  userRole

Step 5: Adding security constraint to web.xml

Now we must create a security constraint and the path to the pages we want to allow only authenticated access. In this sample the access to the folder /pages/ is resticted to authenticated users in role «userRole».


  SecurityConstraint
  
    SecuredFolder
      /pages/*
    
    
      userRole
    
  
    NONE
  

Step 6: Create role mapping between active directory group and role

Role mappings are defined in sun-web.xml for the Sun Java System Application Server, so add the following section:


  userRole
  users

This maps the active directory group «users» to our role «userRole»,
so only users in the group «users» can access our secured folder.

ICEFaces installation for NetBeans IDE

ICEFaces is a Java Server Faces component library. To integrate ICEFaces into the NetBeans IDE and the Visual Web Pack the following steps are necessary.

Download of ICEFaces components

The following downloads from the ICEFaces website are needed:

  • ICEfaces--libs-NetBeans.zip
  • ICEfaces-NetBeans-IDE-.zip
  • ICEfaces--complib-NetBeans.zip

Installation of ICEFaces runtime library

Unpack the file ICEfaces--libs-NetBeans.zip and import the included com-icesoft-ide-netbeans-libs-module.nbm module with the NetBeans Update Manager.

Installation of ICEFaces IDE integration

Unpack the file ICEfaces-NetBeans-IDE-.zip and install the module com-icesoft-faces-vwp-ide.nbm. This module must also be installed with the NetBeans Update Manager.

Installation of ICEFaces component library

Unpack file icefaces-webui.complib from ICEfaces--complib-NetBeans.zip and copy it to your /rave2.0/samples folder.

Import the component library with the Component Library Manager under «Tools->Component Library Manager» into your IDE.

Use of ICEFaces components in a Visual Web Pack project

To use the ICEFaces components in a Visual Web Pack application you must add the ICEFaces Component Suite to your project.