e mërkurë Maj 03, 2006

It's Good to See Your Baby Take Off

My son likes the movie Finding Nemo (I do too:-). The "dude" turtle Crush talks about his offsprings: "You never know when they are ready, but when they know you'll know." It is nice to see your (mental) baby stand up and walk and see its vitality.

When I first started to think about generating simple JSF CRUD applications in NetBeans 5.5 I was not sure if people will like the idea. The vision was to generate a full application without writing any code and to make it literally as simple as possible. For this I had to make some compromises. It is a one way generator - you generate the application from database or from entity classes once, then edit it by hand as you like. It has an extremely simple application model - no backing beans, no EJBs - just JSF, no validation framework, no CSS, it all can be easily added though.

It is great to see NetBeans bloggers to write about it. The GlassFish community says NetBeans took The Rails Lesson. You bet we did :-). Best of all, even long time Eclipse users are comming back to re-evaluate NetBeans!

So why do people like it? I think it's because it creates the application very rapidly, but still gives the developer full control to change anything. It generates code that is meant to be understood and editted by developers. It uses just the standard JSF and JPA. I was hoping that it could help developers in learning JPA and JSF so the code has been reviewed by the Java Blueprints team. You should not fear that you will learn bad design patterns. Expression language code completion added in NetBeans 5.5 helps a great deal to make editing of the generated JSF easy.

Thanks again for the positive blogs. You will see more about this feature and all of NetBeans 5.5 at NetBeans Software Day and at Java One 2006. Stay tuned!

e mërkurë Shk 01, 2006

Next Step: Generate Simple JSF Application

My last blog entry shows a wizard that generates Java Persistence API entity classes from database tables. What was your first question after you tried that wizard? I guess you asked: "OK, what do I do with these classes now? Can I run the application and see them?" I will show you how you can - after you run one more wizard.

The wizard generates a very simple JSF application the follows the CRUD pattern. It lets the user Create, Retrieve (view), Update and Delete data. The generated code includes a JSF managed bean, three JSF pages and some navigation rules in faces-config.xml. The managed bean takes care of access to EntityManager, retrieves and persists entities and also directs navigation between pages. The three JSF pages are: List.jsp, New.jsp and Edit.jsp.

The wizard is launched from File | New File.., select category Persistence and there is JSF Pages from Entity Class. Click next and just select the entity class:

When you finish the wizard you can run the application. Point the browser to a URL of the List page (e.g. http://localhost:8080/GenerateJsf/faces/discountCode/List.jsp) and you will see something like this:

And when you click "New DiscountCode" you will get:

The Edit page is similar...

You can use this for quick testing of your entity classes or as a starting point for your own development. You can also treat it as a simple sample application that shows the whole path from DB to browser. The generated code is very brief and very readable.

To set your expectations correctly, I am writing this only a couple days after I implemented the first version :-). The current version does not support relationships between entity classes, so if your entity classes have relationships you will have to hand code that. I plan to fix this later. I can imagine dozens of ways how this could be improved. But some of them would make it complex, which I want to avoid. Add a comment and tell me what is your opinion and what would be your favorite improvement. Thanks!

e enjte Jan 26, 2006

Generate entity classes from DB

The last entry was about auto generation of DB tables for entity classes in Glassfish. Now, in turn, we have something cool to show you in NetBeans JavaEE 5 build. We have implemented a wizard that generates entity classes from existing database tables. The generator calculates closure of tables based on foreign keys. It generates nice Java friendly names, for example if the database has "CUSTOMER_ID" it will use getCustomerId() for the getter and uses mapping annotations, e.g. @Column(name = "CUSTOMER_ID", nullable = false). It also generates annotations for all relationships, etc.

A picture is worth thousand words:

Get a build of Java EE 5 (see the link in the up right corner) and test it on your database. Send feedback or file bugz. Thanks.

e mërkurë Dhj 07, 2005

Automatic Generation of Database Tables

I've been silent for a looooong time. I wanted to write about use of Java Persistence API in plain Java Applications, about using Hibernate in NetBeans Java EE 5 and do some example that updates data. But Martin Adamek who works with me on Java EE 5 did all the hard work for me :-). Make sure you check his blog!

Today I would like to show a very nice new feature in GlassFish: automatic generation of database tables. In my last demo I started by creating database tables and then I created an entity class to represent the data and a JSF page to display them. Sounds a little complicated if you do not have any existing database to integrate with? You do not even care that much about the specific structure of tables in the database, just want the data stored somehow? This is exactly it.

Start like in the last demo: get a new daily build of NetBeans Java EE 5. You do not need to download Derby plugin from update center, it is now included in NetBeans build. For GlassFish you need a build number 30 from December 7th or newer (get a daily build until build 30 gets promoted).

Create a new web application project and create a persistence unit like we did last time, only this time you need to add two more properties:

<persistence xmlns="http://java.sun.com/xml/ns/persistence">
  <persistence-unit name="pu" transaction-type="JTA">
        <property name="ddl-generation" value="dropandcreate"/>
        <property name="toplink.platform.class.name"

The ddl-generation property tells the application server to generate DDL and create the tables during deployment. There are three accepted values: "createtables", "dropandcreate", "none". The second property specifies the database dialect - for example the database data types used for int, String, etc. (Derby uses a different dialect then for example Oracle).

Start the database and connect to jdbc:derby://localhost:1527/sun-appserv-samples;create=true - this creates the database for the default data source registered in GlassFish. You will also be able to view the tables later - so that you believe me that they were generated.

Now you just create the entity class and the JSF page in the same way. When you deploy the application the table is created and the application works with it. Refresh the tables under the "Databases" node in runtime tab. Voila, you see the new table!

Note that GlassFish also generated a table named SEQUENCE. It is used by the generator of primary keys.

e hënë Nën 14, 2005

Java EE 5 Persistence Demo

I gave you a short primer on Java EE 5 persistence in my last blog entry. Now it's time for a demo. I'll show you how to setup the persistence framework in web application and create a POJO class that represents data from a database table. Then I will execute an EJBQL query to get object from database. In the last step I will use the new JSF component palette to generate a page that displays object in table.

Step 1: Get the Software

I'll be using a NetBeans Java EE 5 daily build from November 13 and build 26 of GlassFish open source Java EE application server, you also need JDK 1.5.

I should repeat that support for Java EE 5 is NOT part of NetBeans 5.0, it will be in the next release of NetBeans and is now being developed on a "javaee5" branch.

Register GlassFish in NetBeans using Tools>Server Manager menu. To register GlassFish use the Sun Java Systems Application Server as a server type. NetBeans will help you to create a new domain for the server, use the "Create Personal Domain" option.

Step 2: Web Application with Persistence Support

Create a new web application project, select GlassFish server and set J2EE version "Java EE 5". Click next and add Java Server Faces support.

Now let's add persistence support into this project. This will be just a few clicks in a wizard, but since I did not cover the persistence unit in the intro let me first describe it here.

Persistence unit defines where and how to persist your classes. The definition of persistence unit consists of:

  • Name and description.
  • Provider: the implementation of persistence API, such as Toplink, Hibernate, etc. If you leave this empty the server will choose the default.
  • Data source, i.e. where the data will be stored and what transaction model will be used.
  • Mapping file is an xml file that defines mappings between database and Java classes. This is useful if you need to define the mapping (we will not do this) and if you do not want to use annotations.
  • A set of classes that this persistence unit applies to. One Java EE module can use multiple persistence units, for example to store data to several different data sources. If you omit this all classes in module will belong to the persistence unit.
  • Properties: a set of name - value pairs of properties. The semantics of these is defined by the provider.

In this example we will only specify the data source. We will use defaults for everything else.

We could specify the parameters of data source directly in your persistence.xml, setting properties like jdbc.connection.string, jdbc.driver, jdbc.user, etc. But in this example I will be using a data source that is defined by the application server, the persistence unit will just reference it by its name. This will make it easier to move the application from one application server and database to another, for example between development, test and production environments.

Now back to our demo. Select menu File>New File (Ctrl+N). Select Persistence Unit template in category Persistence:

Type the name of persistence unit ("demo1"), and keep the default for provider:

Persistence units are defined in persistence.xml file. The content of generated file is:

  <?xml version="1.0" encoding="UTF-8"?>
  <persistence xmlns="http://java.sun.com/xml/ns/persistence">  
    <persistence-unit name="demo1" transaction-type="JTA">

Let's keep the default name of data source jdbc/__default for the demo. Normally you'd go to server admin tool and setup a data source there. But GlassFish has a data source with name jdbc/__default and a derby database connection pool registered. Setup up of database is the next step.

Step 3: Setup the Database

GlassFish bundles derby open source database and this is what I will use for this demo. NetBeans has a module that supports derby. Download the "Derby Database Support" module from the development update center. Use menu Tools>Update Center.

First, start the database using menu Tools>Derby Database>Start Derby Server. Then connect to the database:

The data source jdbc/__default in application server uses the following database URL: jdbc:derby://localhost:1527/sun-appserv-samples;create=true. Use sa for both user name and password and on the next panel select schema APP. This will add a the new connection in Runtime tab and you can execute database scripts on it:

Note the new SQL editor with syntax highlighting, toolbar, etc. that we added in NetBeans 5.0:

Here is the complete script for the table and for inserting some data (insert each line separately). Refresh the list of tables and select View Data from popup menu on DIVECHARTERS table to verify everything is fine. Yes, these are some cool scuba diving trips with my favorite dive shop in Beaufort, NC :-)

Ok, we are done with the database.

Step 4: Persistence Java Class

Click New.. (Ctrl+N) and select Persistence Entity template in category Persistence. Type class name "Divecharters" and package name "data" and click Finish.

Now add properties for table columns:

public class Divecharters {
    private int id;
    private Date departure;
    private String boat;
    private String diveSite;
    private String description;
    private int maxDepth;
    private double price;
    private int capacity;

Use menu Refactor>Encapsulate Fields to create getters and setters for these fields.

Later on NetBeans will support generation of persistence classes from DB tables, similarly as the "CMP from Database" in NetBeans 4.1 and 5.0.

Step 5: Display Objects in JSF Page

We will create a JSF managed bean that will select all instances of Divecharters using EJBQL query. Then we will edit the welcomeJSF.jsp to display them.

Use New.. (Ctrl+N), select the template JSF Managed Bean in category Web. Type class name "PersonController", package "beans" and set scope to "session".

We will use EntityManager the get the persistent data. EntityManager is the central access point to the persistence API. It allows you to create and run queries, persist objects, manage transactions, etc.

The server will inject EntityManager for the PersistenceUnit we defined in Step 2. We will use it to query for all instances of Divecharters class:

public class PersonController {
    EntityManager em;

    public List getCharters() {
        return em.createQuery("select object(d) from Divecharters as d").getResultList();    

This means that our JSF managed bean PersonController will have a property charters. We can now add a JSF data table into welcomeJSF.jsp to render the list of charters. We started to work on a set of templates and palette items to simplify development and prototyping of simple CRUD applications. This is experimental at this point but it comes handy for the demo (give me feedback!). The first preview are two JSF palette items: JSF Form and JSF Data Table:

The code generated in page looks like this:

            <h1><h:outputText value="List"/></h1>
            <h:dataTable value="#{PersonController.charters}" var="item">    
                    <f:facet name="header">
                        <h:outputText value="Id"/>
                    <h:outputText value="#{item.id}"/>
                    <f:facet name="header">
                        <h:outputText value="Departure"/>
                    <h:outputText value="#{item.departure}"/>

Run the application:

e premte Nën 11, 2005

Java EE 5 Persistence

I promised earlier that I will keep you in touch with what new stuff we are working on in Java EE support. Today I would like to write about object relational mapping. This is a very important part of Java EE 5 that we will support in netbeans.next. I will post a tutorial about creating simple persistence classes in a javaee5 preview build soon, so take this as a small intro. It is not a complete description of all features, just a quick overview for someone who is not familiar with this area.

Object relational mapping

Object relational mapping (ORM) is about representing data from database as Java beans. The advantage of using ORM over traditional JDBC is that you do not have to think it terms of database tables, columns, foreign keys, etc. All you use is Java beans, properties and collections of other objects.

Java Persistence API

Java Persistence API (JSR 220) is a new standard API for ORM. Unlike the EJB 2.x entity classes the new persistence API does not require the context of an EJB module and can be used in a web module or even in a Java SE application.

Here is how it compares to some other frameworks for accessing data:

  • JDBC is used by most of the other frameworks as the way to access data in relational databases. But it only provides a lower level of abstraction. If you are working with JDBC you are working with database tables and columns. It does not provide ORM.
  • EJB 2.x entity beans provide ORM but the API is complex. NB 5.0 helps you to manage the multiple classes that represent an EJB plus the deployment descriptor together, but the complexity is still there. Also, the EJB 2.1 entities can only be defined in an EJB module and live in an EJB container. Transfering data outside involves data transfer objects which is just an additional level of complexity.
  • Frameworks like Toplink or Hibernate are powerful and developer friendly but are not a JCP standard. These frameworks surely inspired the new standard and are going to be the big players implementing it. Implementation of JSR 220 in GlassFish application server is based on Toplink architecture, the implementation in JBoss 4.0.3 is based on Hibernate.

How does it work

Java Persistence API does not require the persistent classes to implement any special interfaces, they are just "plain old Java objects" (POJO) marked with annotations.

The mapping between the persistent classes and database tables is also controlled by annotations (or an xml file if you prefer that). But most importantly is has some reasonable defaults, for example a persistent class will be mapped to a table of the same name, its properties will be mapped to columns with the same names, etc. Here is a small example:

public class Person {
    private int id;
    private String name;
    private int age;

    @Id(generate = GeneratorType.AUTO)
    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; 

What if you do need to control the mapping? Let's say the Java class needs to be the same it was but the table is different. You would do something like this:

public class Person {
    @Column (name="EMP_NAME")
    public String getName() {
        return name;

Being POJOs, persistent classes do not need to live within any container. This greatly simplifies writing automated tests or using the persistence classes in combination with other technologies. You can create instances just like this:

   Person p = new Person ();
   p.setId (41);
   p.setName ("Dent Arthur Dent");    

The last nice feature I will mention is that you can write queries to retrieve data from database in terms of Java classes, without reference to the actual relational tables. This is using EJBQL:

      select object(p) from Person as p   

Note that this query will work unchanged even if you map the Person class to table "HR_EMPLOYEES" as shown above.

Persistence API In NetBeans

The basic support for developing persistent classes is in setup and packing of the "Persistence unit" (more about that in the tutorial) and providing templates for persistent classes, code completion for persistence API, etc.

More advanced features we plan to work on include code completion for database metadata (table name, columns, etc.), EJBQL editor, generation of Java classes from an existing database schema, etc.

e premte Nën 04, 2005

Hello JavaEE 5

People have been asking on the nbj2ee@netbeans.org about JavaEE 5 support in NetBeans.

No, it is not part of NetBeans 5.0. Yes, I too wanted everything yesterday :-) but the specs and the application servers are not complete either. Anyway, there are daily builds of the next version of NetBeans available from NetBeans download page which already support creation of EJB 3.0 beans and deployment to GlassFish and Jboss. We will be adding functionality as it gets added into our favorite server and as time permits (we still have some work on NetBeans 5.0).

I wrote a small tutorial about how to get the build and create your first JavaEE 5 application. Check it out and send feedback to nbj2ee@netbeans.org or add comments bellow.

I will be posting more about the progress on JavaEE 5 support in this blog.




« gusht 2016