Posts tagged ‘Tutorial’

ObjectListDataProvider Tutorial

This is a tutorial for using the ObjectListDataProvider in a Visual Web Project. A ObjectListDataProvider is useful if the underlaying data is from a datasource not supported by NetBeans. Some samples for such datasources are a JPA or hibernate connection, other legacy systems such SAP or Lotus Notes and files in various formats.

In this tutorial we use a text file with customer records as datasource for our application.

Creating the project

In the first step you create a normal VWP project named OldpSample:

Project settings OLDP

Address POJO

For data storage we use a simple POJO object. Right click the oldpsample package under «Source Packages» and select «New -> Java Class». Name the class Address.

Create Address class

  1. package oldpsample;
  2.  
  3. public class Address {
  4.  
  5. private String id;
  6. private String title;
  7. private String lastname;
  8. private String firstname;
  9. private String street;
  10. private String city;
  11. private String state;
  12. private String country;
  13.  
  14. /** Creates a new instance of Address */
  15. public Address() {
  16. }
  17.  
  18. public String getId() {
  19. return id;
  20. }
  21.  
  22. public void setId(String id) {
  23. this.id = id;
  24. }
  25.  
  26. public String getTitle() {
  27. return title;
  28. }
  29.  
  30. public void setTitle(String title) {
  31. this.title = title;
  32. }
  33.  
  34. public String getLastname() {
  35. return lastname;
  36. }
  37.  
  38. public void setLastname(String lastname) {
  39. this.lastname = lastname;
  40. }
  41.  
  42. public String getFirstname() {
  43. return firstname;
  44. }
  45.  
  46. public void setFirstname(String firstname) {
  47. this.firstname = firstname;
  48. }
  49.  
  50. public String getStreet() {
  51. return street;
  52. }
  53.  
  54. public void setStreet(String street) {
  55. this.street = street;
  56. }
  57.  
  58. public String getCity() {
  59. return city;
  60. }
  61.  
  62. public void setCity(String city) {
  63. this.city = city;
  64. }
  65.  
  66. public String getState() {
  67. return state;
  68. }
  69.  
  70. public void setState(String state) {
  71. this.state = state;
  72. }
  73.  
  74. public String getCountry() {
  75. return country;
  76. }
  77.  
  78. public void setCountry(String country) {
  79. this.country = country;
  80. }
  81.  
  82. }

Create AddressDataProvider

Now we create the class AddressDataProvider. We create a new class and derive it from ObjectListDataProvider. Right click the oldpsample package under «Source Packages» and select «New -> Java Class».

Create AdressDataProvider class

Our class stores all data in a ArrayList, so we need a member variable of type ArrayList. In the constructor we must tell the underlying ObjectListDataProvider where the data comes from (method setList) and of which type the data is (method setObjectType). We also need methods to load the data from file or stream.

  1. package oldpsample;
  2.  
  3. import com.sun.data.provider.impl.ObjectListDataProvider;
  4. import java.io.BufferedReader;
  5. import java.io.FileInputStream;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.util.ArrayList;
  9.  
  10. public class AddressDataProvider extends ObjectListDataProvider {
  11.  
  12. private ArrayList addressList = new ArrayList();
  13.  
  14. /** Creates a new instance of AddressDataProvider */
  15. public AddressDataProvider() {
  16. setList( addressList );
  17. setObjectType( Address.class );
  18. }
  19.  
  20. public void load(InputStream istream ) {
  21. try {
  22. InputStreamReader sr = new InputStreamReader( istream );
  23.  
  24. while ( br.ready() ) {
  25. String line = br.readLine();
  26. String[] cols = line.split( ";" );
  27.  
  28. if ( cols.length == 8 ) {
  29. Address address = new Address();
  30. address.setId( cols[0] );
  31. address.setTitle( cols[1] );
  32. address.setLastname( cols[2] );
  33. address.setFirstname( cols[3] );
  34. address.setStreet( cols[4] );
  35. address.setCity( cols[5] );
  36. address.setState( cols[6] );
  37. address.setCountry( cols[7] );
  38. getList().add( address );
  39. }
  40. }
  41.  
  42. } catch ( Exception e ) {
  43. e.printStackTrace();
  44. }
  45. }
  46.  
  47. public void load(String filename) {
  48. try {
  49. FileInputStream fs = new FileInputStream( filename );
  50. load( fs );
  51. } catch ( Exception e ) {
  52. e.printStackTrace();
  53. }
  54. }
  55.  
  56. }

Add AddressDataProvider to SessionBean1

In the outline view right click on SessionBean1 and select «Add->Property» from the context menu. Name the property «addressDataProvider» and enter «AddressDataProvider» as Type. Leave all other options on the default values.

New Property addressDataProvider

Double click SessionBean1 in the outline view. Find the line

  1. private AddressDataProvider addressDataProvider;

and change it to

  1. private AddressDataProvider addressDataProvider = new AddressDataProvider();

You must build, close and reopen your VWP project now (as of NetBeans 5.5.1). If not, NetBeans doesn't detect our ObjectListDataProvider. This should hopefully not been necessary in future NetBeans releases.

Design Web Page

The project wizard has generated a default web page Page1.jsp. Open this page and the visual designer starts.

Select a table component from the palette and drop it onto your page. Right click the table component and select «Bind to Data...». Select «addressDataProvider (SessionBean1)» from the dropdown list. Reorder the fields with the «Up» and «Down» buttons, so it look like this:

Select Data Provider

Press «OK» and our page has a table component bound to the AddressDataProvider.

To show some data in the table component we let the user upload a CSV file. Drop a File Upload and a Button component from the palette onto the page. Set the text property of the button to «Upload file». Your page should look like this:

Page Design

Double click on the «Upload file» button and enter the following code into the event handler:

  1. public String button1_action() {
  2. if ( fileUpload1.getUploadedFile().getSize() > 0 ) {
  3. try {
  4. getSessionBean1().getAddressDataProvider().load(
  5. getFileUpload1().getUploadedFile().getInputStream() );
  6. } catch ( Exception e ) {
  7. e.printStackTrace();
  8. }
  9. }
  10. return null;
  11. }

Run your project. Use this sample CSV data file to test the application:

1;Mr.;Able;Tony;216 King St;San Francisco;CA;USA
2;Mr.;Black;Tom;655 Divisadero St;San Francisco;CA;USA
3;Mr.;Kent;Richard;509 Valencia St;San Francisco;CA;USA
4;Mr.;Chen;Larry;407 Ellis St;San Francisco;CA;USA
5;Mrs.;Donaldson;Sue;314 Columbus Ave;San Francisco;CA;USA
6;Mr.;Murrell;Tony;4124 Geary Blvd;San Francisco;CA;USA

This sample project can also be downloaded.

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:

  1. private String customerNo;
  2. private String lastname;
  3. private String firstname;
  4. private String street;
  5. private String postcode;
  6. 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:

  1. private void saveButtonActionPerformed(ActionEvent evt) {
  2. Address address = new Address();
  3. address.setCustomerNo( customerNoText.getText() );
  4. address.setLastname( lastnameText.getText() );
  5. address.setFirstname( firstnameText.getText() );
  6. address.setStreet( streetText.getText() );
  7. address.setPostcode( postcodeText.getText() );
  8. address.setCity( cityText.getText() );
  9.  
  10. EntityManagerFactory emf = Persistence.createEntityManagerFactory(
  11. "JPATutorialPU" );
  12. EntityManager em = emf.createEntityManager();
  13. em.getTransaction().begin();
  14.  
  15. try {
  16. em.persist( address );
  17. em.getTransaction().commit();
  18. } catch (Exception e) {
  19. System.out.println( e.getMessage() );
  20. em.getTransaction().rollback();
  21. } finally {
  22. em.close();
  23. }
  24. }

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:

  1. private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {
  2.  
  3. EntityManagerFactory emf = Persistence.createEntityManagerFactory(
  4. "JPATutorialPU" );
  5. EntityManager em = emf.createEntityManager();
  6. em.getTransaction().begin();
  7.  
  8. String customerNo = JOptionPane.showInputDialog(
  9. null,
  10. "Enter customer number",
  11. "Input",
  12. JOptionPane.QUESTION_MESSAGE);
  13.  
  14. try {
  15. Query query = em.createQuery(
  16. "SELECT a FROM Address a WHERE a.customerNo = :customerNo");
  17. query.setParameter(
  18. "customerNo",
  19. customerNo);
  20.  
  21. Address address = (Address) query.getSingleResult();
  22.  
  23. customerNoText.setText( address.getCustomerNo() );
  24. lastnameText.setText( address.getLastname() );
  25. firstnameText.setText( address.getFirstname() );
  26. streetText.setText( address.getStreet() );
  27. postcodeText.setText( address.getPostcode() );
  28. cityText.setText( address.getCity() );
  29.  
  30. } catch (Exception e) {
  31. System.out.println( e.getMessage() );
  32. em.getTransaction().rollback();
  33. } finally {
  34. em.close();
  35. }
  36. }

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.