18
4 Chapter 4: Getting started with Eclipse and PostgreSQL Getting started with Eclipse and PostgreSQL chapter4

Openxava by Example Chapter4

Embed Size (px)

DESCRIPTION

OpenXava , open source tutorial , web developing

Citation preview

Page 1: Openxava by Example Chapter4

4 Chapter 4: Getting started with Eclipse and PostgreSQL

Getting started with Eclipse and PostgreSQL

chapter4

Page 2: Openxava by Example Chapter4

Chapter 4: Getting started with Eclipse and PostgreSQL 36

This chapter is the kick off to your first OpenXava application. After a brief revision of the application that we wish to develop, we shall configure all the tools that you need to develop an OpenXava application.

You are going to install PostgreSQL and Eclipse, configure Tomcat inside Eclipse and create the project for your application.

This chapter is used as an introduction to OpenXava, PostgreSQL and Eclipse. Keeping introduction in mind, this chapter is a little over explanatory, especially about the Eclipse IDE. So, if you are an already seasoned Eclipse user, just take a cursory look at this chapter, and go directly to the next chapter.

4.1 Our goal: A small Invoicing applicationThe application chosen is a small Invoicing application with invoices,

customers, products and so on. This application is just a brief way to learn some typical cases in business applications. You can apply everything you learn with the invoicing application to any other business application of any other domain.

On the other hand, this invoicing application is a didactic tool. You are advised not to use it “as is” for a real invoicing system.

4.2 Installing PostgreSQLWe are going to use PostgreSQL as the database server for your first

application. We have chosen PostgreSQL because it's an open source high quality product and is also very popular.

Go to the download section of www.postgresql.org, choose the pre-built binary package to your platform and download it.

First, install it for Linux/Unix by executing the downloaded file, as shown in listing 4.1.Listing 4.1 Launching PostgreSQL installer in Linux$ suPassword:$ chmod +x postgresql-8.3.7-1-linux.bin$ ./postgresql-8.3.7-1-linux.bin

If you are using Windows Vista you have to turn off UAC in order to install PostgreSQL. Just follow these steps:

• Go to Control Panel.

• In Control Panel, click User Accounts.

Page 3: Openxava by Example Chapter4

37 Chapter 4: Getting started with Eclipse and PostgreSQL

• In the User Accounts window, click User Accounts.

• In the User Accounts tasks window, click Turn User Account Control on or off.

• If the User Account Control message appears just click on Continue.

• Uncheck the Use User Account Control (UAC) to help protect your computer check box, then click OK.

• Click Restart Now to apply the change.

To start the wizard in Windows (any version) just double click on postgresql-8.3.7-1-windows.exe.

You only have to follow a simple wizard by clicking the 'Next' button until the end. The table 4.1 shows you the wizard steps.

Description Screenshot1 Presentation page

2 Installation directory for PostgreSQL.You can leave the default one

3 Directory for data.You can leave the default one

4 Password for 'postgres' user.Type 'openxava', for example

5 The port. Leave the default

6 The locale.You can leave the default one

Table 4.1 Wizard steps to install PostgreSQL

Page 4: Openxava by Example Chapter4

Installing PostgreSQL 38

Description Screenshot7 Before starting the installation

8 Wait while PostgreSQL is installed

9 Now PostgreSQL is installed

Table 4.1(cont.) Wizard steps to install PostgreSQL

After following the steps mentioned in table 4.1, PostgreSQL is installed on your machine. The next step is to create a new database and start the PostgreSQL server. For Linux/Unix follow the instructions in listing 4.2Listing 4.2 Creating a new database and starting PostgreSQL server on Linux/etc/init.d/postgresql-8.3 start # Starts dbexit # You do not need root rights from now on/opt/PostgreSQL/8.3/bin/createdb -Upostgres invoicing # Creates a new database

# named 'invoicing'

On Windows type the instructions in listing 4.3 from the Command Prompt (cmd.exe) of your Windows.Listing 4.3 Creating a new database on Windows from the Command Prompt"C:\Program Files\PostgreSQL\8.3\bin\createdb" -Upostgres invoicing

The PostgreSQL server is registered as a service, so it is started and it will be started automatically every time you start your computer.

If you're using Windows Vista you can turn on UAC again if you wish.

At this point you have created a new database named 'invoicing', and you have started the PostgreSQL database server. Your database is ready to use. Let's create the application.

4.3 Creating the project in EclipseUndoubtedly Eclipse (alternatively NetBeans) is the ubiquitous IDE in the

Java world. OpenXava comes out of the box ready to be used with Eclipse. You are going to develop your invoicing application using Eclipse. At the end of this chapter you'll have a first working version of your application developed as an Eclipse project.

This book assumes that you are using the “Eclipse IDE for Java EE

Page 5: Openxava by Example Chapter4

39 Chapter 4: Getting started with Eclipse and PostgreSQL

Developers” edition of Eclipse with Java 5 or better. If needed, get Eclipse from www.eclipse.org and Java from www.java.com.

4.3.1 Installing OpenXava

Go to www.openxava.org and download the latest OpenXava distribution. It is a zip file something like openxava-4.0.zip4. Just uncompress it, and you will have an environment ready to start developing. Look it at figure 4.1.

As you see, OpenXava distribution includes Tomcat and an Eclipse workspace, all configured and ready to use. Let's start to work.

4.3.2 Create the project

Creating a new OpenXava project is simple. Just create a regular Java project with Eclipse, and then execute an ant target.

Start your Eclipse and open the OpenXava workspace with it (File > Switch Workspace). First, you have to create a new Java project. Click on the button for creating a new Java project (figure 4.2), then a wizard will appear. Just type the project name, Invoicing, and click the Finish button (figure 4.3).

4 Although the screenshots in this book are from OpenXava 3.1.4, all the code has been tested with OpenXava 4

Figure 4.1 OpenXava distribution content

All doc from w iki in HTML. It includes Reference Guidein English, Spanish, French,Russian and Chinese API doc of OpenXava

Reference Guide in PDF forEnglish, Spanish and FrenchTomcat conf igured w ith jars

and databases ready for run allOpenXava demo

Utility project. You can use itif you need to track all changesthe users do to the dataSimple demos for tutorial

Template projects for creatingnew OpenXava projects

OpenXava framew ork

Project to test OpenXava robustness

Ready to use Eclipse w orkspace

Figure 4.2

Click here to create a new Java project

Page 6: Openxava by Example Chapter4

Creating the project in Eclipse 40

After this step you have an empty Java project named Invoicing (figure 4.4). Now you must convert it into an OpenXava project. Go to the CreateNewProject.xml file of the OpenXavaTemplate project, and run it as an ant build (figure 4.5).

Now you have to type the project name. Just type “Invoicing” and click OK (figure 4.6). Wait a few second until the ant build finishes. Then select Invoicing project in your Eclipse, and press F5 to refresh it. Now you have a full OpenXava project there.

We are going to configure the Tomcat inside your Eclipse to use it as a platform for running your application.

Figure 4.3 New Java project

And then click on Finish

Type Invoicing as project name

Figure 4.4 Empty Java project

Figure 4.5 Running CreateNewProject ant build

Figure 4.6 After ant execution you get an OpenXava project

Type “Invoicing” w hen ant ask you the project name

After ant execution Invoicing project is anOpenXava project

Page 7: Openxava by Example Chapter4

41 Chapter 4: Getting started with Eclipse and PostgreSQL

4.3.3 Configuring Tomcat inside Eclipse

Starting Tomcat from Eclipse has several advantages such as you can debug, see the log messages and traces inside Eclipse, go from trace to code in a click, etc.

Adding Tomcat as a runtime server to Eclipse

Go to the Eclipse option menu Windows > Preferences > Server > Runtime Environments. This will show you the wizard in figure 4.7.

Adding a Tomcat server to Eclipse

After following the instruction in figure 4.7, you have Tomcat added to your Eclipse as a runtime environment. Now you have to create a server that uses this runtime environment. Go to the Eclipse menu Window > Show View > Other. And follow the instructions in figure 4.8. After that, you have a Tomcat server configured in your Eclipse.

Figure 4.8 Steps to add a Server to Eclipse

1. Add the Servers view 2. Add a new server f romServer view

3. A w izard is show n,just click on Finish

Figure 4.7 Wizard to add Tomcat as server runtime to Eclipse

1. Choose Apache Tomcat v6.0

2. Click Next

3. As Tomcat installation directory use the Tomcat included w ith OpenXava

4. Click Finish

Page 8: Openxava by Example Chapter4

Creating the project in Eclipse 42

Creating the data source

A data source is the way an application server knows how to connect to a database. From our applications we only reference the data sources (and not the databases directly), so we have to configure the data sources in Tomcat to point to the correct databases. Let's define the data source for our Invoicing application.

Go to the Servers project of Eclipse, edit the file context.xml inside the folder of your server (figure 4.9).

In context.xml you have to add a new data source called InvoicingDS against your PostgreSQL database. Just add the code in listing 4.4 at the end of context.xml just before the last </Context> mark.Listing 4.4 Data source definition to add to context.xml of Tomcat inside Eclipse<Resource name="jdbc/InvoicingDS" auth="Container"

type="javax.sql.DataSource"maxActive="20" maxIdle="5" maxWait="10000"username="postgres" password="openxava" driverClassName="org.postgresql.Driver"url="jdbc:postgresql://localhost/invoicing"/>

In order to make this data source work you need to add the PostgreSQL driver to your Tomcat. Open your internet browser and go to jdbc.postgresql.org site, then download the PostgreSQL jdbc driver. It is a jar file. After downloading, copy it to the lib folder of your Tomcat (in openxava-4.x.x/tomcat).

Add Invoicing application to the Tomcat server

Your Tomcat is just configured to connect to your PostgreSQL database. Now, the only thing remaining is to add your Invoice application to Tomcat.

In order to add your application to Tomcat go to the Servers view and follow the instruction as shown in figure 4.10.

Figure 4.9 Edit context.xml to add data sources

Page 9: Openxava by Example Chapter4

43 Chapter 4: Getting started with Eclipse and PostgreSQL

After that, your project is ready to run in Tomcat. And you are ready to write you first entity and run your application for the first time.

4.3.4 Creating your first entity

At last you have your development environment configured. Now, developing the application is very easy. You only have to add entities in order to make your application grow. Let's create your first entity, and run the application.

First, you have to create the package to contain the model classes (the entities). Follow the instruction in figure 4.11 to create a package named org.openxava.invoicing.model.

You have learned how to create a Java package in Eclipse. From now on we won't use a figure for that.

Now, you can create your first entity. We start with a simple version of

Figure 4.10 Adding Invoicing application to Tomcat server

1. Right-button on the server

2. Choose Add and Remove Projects

3. Choice Invoicing

4. Click Add, it w ill move to right column

5. Click on Finish

Figure 4.11 Creating the new package 'org.openxava.invoicing.model'

1. Invoicing > src > New > Package

2. Type the package name

3. Click on Finish

Page 10: Openxava by Example Chapter4

Creating the project in Eclipse 44

Customer with only number and description. Follow the instruction in figure 4.12 to create a new Customer class.

You have learned how to create a Java class in Eclipse. From now on we won't use a figure for that.

The initial code that Eclipse provides for Customer is pretty simple, see it in listing 4.5.Listing 4.5 The initial naked class that Eclipse creates for Customerpackage org.openxava.invoicing.model;

public class Customer {

}

Now, you have to fill this class in order to convert it to an entity suitable for OpenXava. You only need to add the @Entity annotation, the number and the description properties. Just as you can see in listing 4.6.Listing 4.6 The first version of Customer entitypackage org.openxava.invoicing.model;

import javax.persistence.*;import org.openxava.annotations.*;

@Entity // This marks Customer class as an entitypublic class Customer {

@Id // The number property is the key property. Keys are required by default@Column(length=6) // The column length is used at the UI level and the DB levelprivate int number;

Figure 4.12 Creating the new class 'Customer'

1. Select the package

2. Click on 'New Java Class' button

3. Type the class name

4. Click on Finish

Page 11: Openxava by Example Chapter4

45 Chapter 4: Getting started with Eclipse and PostgreSQL

@Column(length=50) // The column length is used at the UI level and the DB level@Required // A validation error will be shown if the name property is left emptyprivate String name;

public int getNumber() {return number;

}

public void setNumber(int number) {this.number = number;

}

public String getName() {return name;

}

public void setName(String name) {this.name = name;

}

}

At last you have enough code (just one class) to run your application. Let's run it.

4.4 Preparing the databaseAn empty database has been created for your application. Now you need to

create the required database tables. For now it is a table for customers.

First, make sure that your PostgreSQL database is up. If not, start it using the line in listing 4.7 from the command line of your operating system.Listing 4.7 Starting PostgreSQL in Linux/opt/PostgreSQL/8.3/bin/postgres -D /opt/PostgreSQL/8.3/data # Starts db

In the case of Windows PostgreSQL has been defined as a service, so it's started by default. You can stop and start PostgreSQL from Control Panel > Administrative Tools > Services of your Windows.

4.4.1 Configuring persistence.xml

You have to configure your application to go against your database. For that, modify the persistence.xml file that you can find in Invoicing/persistence/META-INF folder. Edit it, remove the existing persistence units and add the ones in listing 4.8.Listing 4.8 The persistence.xml file with the configured persistence units<?xml version="1.0" encoding="UTF-8"?>

Page 12: Openxava by Example Chapter4

Preparing the database 46

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

<!-- Tomcat + PostgreSQL --><persistence-unit name="default"><non-jta-data-source>java:comp/env/jdbc/InvoicingDS</non-jta-data-source><class>org.openxava.session.GalleryImage</class>

<properties><!-- PostgreSQL dialect --><property name="hibernate.dialect"

value="org.hibernate.dialect.PostgreSQLDialect"/></properties>

</persistence-unit>

<!-- JUnit PostgreSQL --><persistence-unit name="junit">

<properties> <!-- PostgreSQL driver class --><property name="hibernate.connection.driver_class"

value="org.postgresql.Driver"/>

<!-- PostgreSQL dialect --><property name="hibernate.dialect"

value="org.hibernate.dialect.PostgreSQLDialect"/>

<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/invoicing"/>

<!-- The user of the database --><property name="hibernate.connection.username" value="postgres"/>

<!-- The password of the user of the database --><property name="hibernate.connection.password" value="openxava"/>

</properties> </persistence-unit>

</persistence>

The default persistence unit is the one used for accessing the database from the application. This occurs inside Tomcat. The junit persistence unit is used by the junit tests and the “update schema” tool, that is from inside Eclipse.

4.4.2 Update schema

Every time we make changes in the structure of our model for example creating new entities, persistent properties, references or collections, we need to update the database schema. For example, in this case you need a new table for Customer with two columns one for number and the other one for description.

Page 13: Openxava by Example Chapter4

47 Chapter 4: Getting started with Eclipse and PostgreSQL

Configuring updateSchema

It's possible to automatically update your database schema from your entities. This is achieved by means of the updateSchema ant target from Invoicing/build.xml. Before using it for the first time you need to put the path to your JDBC driver. Edit the Invoicing/build.xml file and look for the updateSchema target and then edit the same to leave it as in listing 4.9.Listing 4.9 Modifying updateSchema to point to the PostgreSQL driver<target name="updateSchema">

<ant antfile="../OpenXava/build.xml" target="updateSchemaJPA"><property name="persistence.unit" value="junit"/><!-- The path of your JDBC driver --><property name="schema.path" value=

"/openxava-4.0/tomcat/lib/postgresql-8.3-604.jdbc3.jar"/>

</ant></target>

You have to put the path to your PostgreSQL JDBC driver as the value for schema.path.

Now the updateSchema is ready to be used.

Executing updateSchema

Let's create the database table automatically. First, press Control-B in order to do a build of your project; then follow the instructions in figure 4.13.

After executing updateSchema you will see a console view in your Eclipse like the one in figure 4.14.

Figure 4.13 Executing updateSchema

1. Invoicing > build.xml > Run As > Ant Build... 2. Unselect any selected target3. Select updateSchema4. Make sure of updateSchema is the only target5. Click on Run

Page 14: Openxava by Example Chapter4

Preparing the database 48

By now you have learned how to create and update the database schema from your entities. From now on we won't use a figure for that. Remember, every time your entities structure changes you must execute updateSchema again. You can re-execute easily the updateSchema ant target using the External Tools button (figure 4.15).

The updateSchema ant target is based on Hibernate Tools.

Now that you have the table for Customer created you can, finally, execute your application.

4.5 Running the applicationFirst, start your server following the instructions in figure 4.16.

Your application is already running. To check this, open your browser and go to the URL:

http://localhost:8080/Invoicing/modules/Customer

Now, you get your application running for the first time. Use it to create new customers as indicated in figure 4.17.

Figure 4.16 Starting Tomcat Server inside Eclipse

1. Go to Server view

2. Choose the server

3. Click on 'Start the server'

Figure 4.14 Result of schemaUpdate: Customer table is created

Customer table created

Figure 4.15 External Tools

Page 15: Openxava by Example Chapter4

49 Chapter 4: Getting started with Eclipse and PostgreSQL

Congratulations, you have your environment configured and your application running.

4.6 Modifying the applicationFrom now on, developing the application with OpenXava is very easy. Just

write a class, update the database schema and go to your browser to see the result. Let's try it.

Create a new entity for Product with the code in listing 4.10. If you do not remember how to do so then please revisit the above section 4.3.4.Listing 4.10 The first version of Product entitypackage org.openxava.invoicing.model;

import javax.persistence.*;

import org.openxava.annotations.*;

@Entitypublic class Product {

@Id @Column(length=9)private int number;

@Column(length=50) @Requiredprivate String description;

public int getNumber() {return number;

}

public void setNumber(int number) {this.number = number;

}

public String getDescription() {

Figure 4.17 Use the Customer module to add new customers

1. Click on New button

2. Type the number and name

3. Click on Save button

List mode Detail mode

Page 16: Openxava by Example Chapter4

Modifying the application 50

return description;}

public void setDescription(String description) {this.description = description;

}

}

Now, press Ctrl-B (to build the project), update the database schema (follow the instructions in section 4.4.2), open your browser and go to the URL:

http://localhost:8080/Invoicing/modules/Product

Yes, you have a new module running, and you only needed to write a simple class. Now you can concentrate on growing your application.

4.7 Accessing a database from EclipseThough you already have every tool you need to develop your application in

place, sometimes it's useful to execute SQL statements directly against your database. You can do it from inside Eclipse. This section will help you to setup your Eclipse to do so.

First, follow the instruction in figure 4.18 to change to the Database Development perspective inside Eclipse.

Figure 4.18 Changing to Database Development perspective in Eclipse

1. Click on 'Open Perspective'

2. Choose 'Other'

3. Select 'Database Development'

4. Click on OK

Page 17: Openxava by Example Chapter4

51 Chapter 4: Getting started with Eclipse and PostgreSQL

Now create a New Connection Profile following the instruction in figure 4.19.

Figure 4.19 Adding a New JDBC Connection Profile

1 31. Click on New

Connection Prof ile button of Data Source

Explorer view

2

6

45

2. Choose PostgreSQL,type 'Invoicing' as name

and click on Next

3. Click on New Driver Def inition button

4. Select PostgreSQL andchange to Jar List tab

5. Edit jdbc driver jar to pointto the correct place in your

computer

6. Entry the connection properties,click on Test Connection,

andif it w orks click on Finish

The passw ord is 'openxava'

Page 18: Openxava by Example Chapter4

Accessing a database from Eclipse 52

Now you can execute any SQL statement you want. To do so you have to open a scrapbook. Follow the instructions in figure 4.20 to do so.

From now on, you only have to change to the Database Development perspective in your Eclipse to execute any SQL you want. You can even add the Data Source Explorer view to the Java perspective if you like.

This Eclipse Database Development tool is only an option. If you are used to another tool to manage your PostgreSQL database just use it.

4.8 SummaryAfter this chapter you have installed PostgreSQL, Eclipse and OpenXava.

Moreover, you have configured everything in order to work. Now, you have your environment ready to develop your application.

Also, you have the very first version of your Invoicing application running.

But the most important thing is that you have learned how to create a new project, a new package, a new class, how to update the database schema, how to run an OpenXava module and other useful things that you will need to use in the rest of the book.

Figure 4.20 Executing a SQL statement using SQL scrapbook

1. Choose invoicing database

2. Click on Open scrapbook

3. Type your SQL statement

5. See the results on SQL Result view

4. Right button > Execute all