Thursday Oct 23, 2008

MySQL Improvements in NetBeans 6.5

Here's a new vid from Andrei Badea on the new MySQL support in NetBeans 6.5. Enjoy!

<script type="text/javascript" src="http://www.netbeans.tv/js/swfobject.js"></script> <script type="text/javascript"> </script>

Monday Oct 13, 2008

NetBeans Platform Training Taking Off

Geertjan is just back from a trip around Europe giving the NetBeans Platform Training to various institutions. He was joined by Petr Suchomel for an in-house training at an ISV, then David Strupl and Dream Team member Toni Epple at the University of W├╝rzburg. He also stopped off at a JUG in Dresden on the way back to Prague.

We've been blown away by the demand for the NetBeans Platform Training. Businesses that are already building on the platform want us to come help them expand their knowledge. Universities love it because it offers a real-life application of Java concepts and skills. In fact, we've had so much interest that we just can't keep up. (We're working on a NetBeans module that clones Geertjan, Petr, Jarda, and other Platform experts, but so far it's only in Alpha.)

That's why it's so awesome to have the community come help us give these trainings. It's not just that it helps us deal with the load of training demands - it gives us a valuable insight into how the APIs are used. We have written the APIs, but few people inside Sun have used them for anything other than writing IDE modules. So having someone who has actually used the APIS for doing RCP apps makes for a much better class.

If you're interested in the course, check out the main NetBeans Platform Training page. Also check out what Toni (with pictures) and Geertjan had to say about the course.

Tuesday Oct 07, 2008

New Demo - Using EclipseLink with JPA in a web application

This comes from Troy Giunipero, docs writer here in Prague for NetBeans. It's a great screencast on using EclipseLink with the Java Persistence API in a web app. Check it out.

<script type="text/javascript" src="http://www.netbeans.tv/js/swfobject.js"></script> <script type="text/javascript"> </script>

Check out more web application tutorials and demos from netbeans.org.

Wednesday Oct 01, 2008

Cool PHP Demos in NetBeans

I've been looking at the excellent work that people have been doing at the NetBeans PHP Blog and especially at the excellent screencasts and video tutorials that Petr Pisl has been putting out. He's got a Demo on using class property variables and a great demo about developing WordPress plugins with NetBeans. This along with Roman's slightly outdated but still great PHP Editor Demo gives you a nice overview of the PHP functionality that you can watch while drinking your morning coffee.

Wednesday Jun 07, 2006

More Automatic JSF Generation

In addition to generating a whole CRUD application using JSF and the Java Persistence API, NetBeans IDE 5.5 dev builds also have some cool JSF generation features. I'm trying to tie everything up before going on vacation (two weeks in Spain - BRING IT!!!) and I was filling in some online help on this feature, so I thought I'd share it.

So let's say you don't want to generate a whole CRUD app, but you do want to generate a form for getting user information and storing it in a database. You'd want to create an entity class for the user information, (let's say a Book class with bean properties for author, title, and genre) and a JSF managed bean that acts a controller (methods for returning all books, saving a new book in the database, etc.). Maybe these things already exist, the developer who handles the DB and back-end has already set them up, and your job is just doing the front-end.

So you open up your web app, create a new JSP page called addbook.jsp. Then you drag the JSF Form palette item into the JSP and release. You get this dialog box, where you fill in the class name and specify you want an editable form (you want to create a new book, not just show the data from an existing book):

Press OK and you get this:

<f:view>
    <h2>Create</h2>
    <h:form>
        <h:panelGrid columns="2">
            <h:outputText value="Title:"/>
            <h:inputText id="title" value="#{anInstanceOfdb.book.Book.title}" title="Title" />
            <h:outputText value="Author:"/>
            <h:inputText id="author" value="#{anInstanceOfdb.book.Book.author}" title="Author" />
            <h:outputText value="Genre:"/>
            <h:inputText id="genre" value="#{anInstanceOfdb.book.Book.genre}" title="Genre" />
        </h:panelGrid>
    </h:form>
</f:view>

Now you need to change anInstanceOfdb.book.Book to a property in the controller class that represents an instance of a single book. Supposing you've got your controller class registered as a JSF managed bean with the name book, it might look something like this:

<f:view>
    <h2>Create</h2>
    <h:form>
        <h:panelGrid columns="2">
            <h:outputText value="Title:"/>
            <h:inputText id="title" value="#{book.book.title}" title="Title" />
            <h:outputText value="Author:"/>
            <h:inputText id="author" value="#{book.book.author}" title="Author" />
            <h:outputText value="Genre:"/>
            <h:inputText id="genre" value="#{book.book.genre}" title="Genre" />
        </h:panelGrid>
    </h:form>
</f:view>

You'd then add a commandButton to submit the form. Run it and here's what you get:

Pretty handy, especially when you've got a lot of user information you have to fill in. Note that you can also use the Read-only function to just present all of the data for an existing book as well.

Thursday Jun 01, 2006

Quickly Adding a Navigation Rule and Navigation Case

Short and sweet revelation regarding setting JSF navigation in faces-config.xml. I thought in NetBeans IDE 5.5 you had to first add a navigation rule with the Add Navigation Rule command, then add a navigation case separately with the Add Navigation Case command.

Actually, you can do both at once by just going to Add Navigation Case right off the bat. If a navigation rule for the page you specified in From View already exists, the IDE'll add the case to that rule. If it doesn't exist, it'll create it.

Which begs the question, why do you need the separate Add Navigation Rule command at all? Would you ever want to create an empy navigation rule? Or is this just for discoverability? I could see a user saying "I can't create a navigation case yet, I haven't even defined the navigation rule!"

All of these puny revelations are brought to you from testing some very cool short tutorials which you shall soon see from the Java EE Tutorials team. So stay tuned!

Wednesday May 31, 2006

XHTML, Facelets, and NetBeans IDE

I was trying to do the Facelets tutorial in NetBeans IDE, and the tutorial calls for lots of XHTML files. Unfortunately, NetBeans makes it very hard to create XHTML pages with the .xhtml suffix.

First I had to actually find the XHTML template. It's not under Web, which is strange because HTML is there. After searching (OK, Geertjan told me), I found it in the Other category. Problem solved, right? Wrong.

The XHTML File Wizard doesn't let you specify the extension and automatically gives an XHTML file an .html extension, although it correctly recognizes it as an XML file and not a regular HTML file.

So the only way to really do this is to register the .xhtml extension as belonging to XML files. Choose Tools > Options > Advanced Options > IDE Configuration > System > Object Types > XML Objects and add .xhtml to the Extension and MIME Types category. (Side note - this setting really needs to get promoted to the main Options panel. It's one I use quite a bit and it's terribly buried in the Advanced Options. Actually, I'd rather be able to right-click any unrecognized file and choose Treat As... to register the extension with an object type.)

Now that the extension's registered, use the Other > Empty File template. This is the only template that will allow you to specify an extension. Give the file the .xhtml extension and it'll show up correctly as a file, although not with any of the skeleton code. It'll just be an empty file. Better than nothing, though.

BTW - if you're trying to do facelets in NetBeans IDE, it's not really easy. There's no code completion in the XHTML files, since schema-based code completion hasn't been implemented yet. If you use jspx files, it's supposed to work, but last I looked at it code completion wasn't working there either. Check out Mark Overdij's blog for a quick run-through of getting it going.

Tuesday May 30, 2006

GlassFish Samples Integrated in NetBeans 5.5

This has been the case for a few weeks now, but I just noticed it now. There are lots more Java EE samples in NetBeans, thanks to the integration of the GlassFish samples. On the Welcome Screen, just click Java EE 5 under Samples, and you can access the following samples:

Friday May 26, 2006

Validating an Email Address in JSF

In earlier installments of the jAstrologer tutorial (see previous blogs) we used a converter and standard validators to validate the input in inputText components. You can also code your own validators if the standard JSF validatiors do not work for you. In our example, we will code a validator that checks a string to see if it is a valid email. To create a custom validator, you create a class that implements the javax.faces.validator.Validator interface and register the class in faces-config.xml. You can then use the validator using the <f:validator> tag.

  1. Right-click the project node and choose New > Java Class. Name the class EmailValidator, place it in the astrologer.validator package, and click Finish.
  2. In the class declaration, implement Validator as follows:
    public class EmailValidator implements Validator {
  3. Use the hint to implement the validate method.

  4. Add the following code to the validate method:
        public void validate(FacesContext facesContext, 
                UIComponent uIComponent, Object object) throws ValidatorException {
            
            String enteredEmail = (String)object;
            //Set the email pattern string
            Pattern p = Pattern.compile(".+@.+\\\\.[a-z]+");
            
            //Match the given string with the pattern
            Matcher m = p.matcher(enteredEmail);
            
            //Check whether match is found
            boolean matchFound = m.matches();
            
            if (!matchFound) {
                FacesMessage message = new FacesMessage();
                message.setDetail("Email not valid");
                message.setSummary("Email not valid");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
        }
    
  5. Open faces-config.xml and add the following code:
         ...
        </application>
        <validator>
            <validator-id>astrologer.EmailValidator</validator-id>
            <validator-class>astrologer.validate.EmailValidator</validator-class>
        </validator>
    </faces-config>
  6. Open greeting.jsp and add the email field:
         ...
            <p>Enter your name: <h:inputText value="#{UserBean.name}" 
            id="name" required="true"/>
            <h:message for="name" /></p>
            <p>Enter your email: <h:inputText value="email" 
            id="email" required="true">
                <f:validator validatorId="astrologer.EmailValidator" />
            </h:inputText>
            <h:message for="email" /></p>
            <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" 
                id="birthday" required="true">
         ...
  7. Run the project. When you enter a non-valid email in the field, you get the following error:

Thursday May 25, 2006

jAstrologer JSF Tutorial - Custom Validation in the Backing Bean

Although performing validation using required fields and converters is easy, it is also very limited. The error messages are not formatted very nicely and the checking that you can perform is limited. We can acheive more fine-tuned validation and better display of errors by coding validation into our backing bean.

For example, the converter checks that the birthday field is a valid date, but it doesn't check that the date was in the past. We are now going to check for this case in our custom validation and list any errors at the top of the page in a bulleted list.

  1. Open UserBean.java and make the following changes in bold:
    public class UserBean {
        
        private String name = "";
        private Date birthday;
        private ArrayList errors = new ArrayList();
        
    	...
    	    
        public String getErrors() {
            String message;
            if (errors.size() == 0) {
                message = "";
            } else {
                message = "<FONT COLOR=RED><B><UL>\\n";
                for(int i=0; i<errors.size(); i++) {
                    message = message + "<LI>" +
                            (String)errors.get(i) + "\\n";
                }
                message = message + "</UL></B></FONT>\\n";
            }
            return(message);
        }
        
        public String submit() {
            if (birthday == null) {
                errors.add("Valid birthday required");
            }
            else if (birthday.getTime() > new Date().getTime()) {
                errors.add("Birthday must be some time in the past");
            }
            if (name == "") {
                errors.add("Name required");
            }
            if (errors.size() > 0) {
                return(null);
            } else {
                return("submit");
            }
        }    
        
    }
  2. Open greeting.jsp and make the following changes in bold:
        <f:view>
            <h:form>
                <h:outputText value="#{UserBean.errors}" escape="false"/>
                <p>Enter your name: <h:inputText value="#{UserBean.name}" /></p>
                <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" >
                    <f:convertDateTime pattern="dd/MM/yyyy" />
                </h:inputText> (dd/mm/yyyy)</p>
                <h:commandButton value="Submit" action="#{UserBean.submit}" />
            </h:form>
        </f:view>
  3. Run the project and click Submit without entering any data. You get the following error:

    nicely formatted errors

Wednesday May 24, 2006

More JSF Validation - Custom Error Messages

The errors messages that are shown for each type of validation error are controlled by the Message.properties file, which is located in the javax.faces package of jsf-impl.jar. You can view this file by expanding Libraries > Sun Java System Application Server > jsf-impl.jar > javax.faces and double-clicking Message.properties.

If you want to create custom messages for these errors, you can do so by swapping out the properties file used by the application.

  1. Right-click the jAstrologer project and choose New > File/Folder. Under the Other category, select Properties File and click Next. Name the file MyMessages, put it in the src/astrologer/ui folder, and click Finish. MyProperties.properties opens in the Source Editor.
  2. Copy over the following properties from Message.properties to MyProperties.properties:
    javax.faces.component.UIInput.REQUIRED={0}: Validation Error: Value is required.
    javax.faces.converter.DateTimeConverter.DATE_detail={2}: ''{0}'' could not be understood as a date. Example: {1}
  3. Change the values of the properties:
    javax.faces.component.UIInput.REQUIRED=Please enter a value for this field.
    	javax.faces.converter.DateTimeConverter.DATE=Please enter a valid date. 
    javax.faces.converter.DateTimeConverter.DATE_detail=Please enter a valid date. Example: {1}
  4. Open faces-config.xml (under the Configuration Files node) and enter the following inside the main faces-config element:
        ...
        <application>
            <locale-config>
                <default-locale>en</default-locale>
            </locale-config>
            <message-bundle>astrologer.ui.MyMessages</message-bundle>
        </application>
    </faces-config>
  5. Right-click the application and choose Run Project. When you do not enter anything for a required field or enter a bad date format for the birthday field, the application now shows the following errors:

    custom errors

    Note that any messages that you haven't specified in your custom properties file will be taken from the default Message.properties in jsf-impl.jar. Also, you can define a CSS style for error messages and then specify that style in the message tag by doing the following:

    <h:message for="birthday" style="errorMessage" /></p>

Tuesday May 23, 2006

jAstrologer JSF Tutorial - Validaiton Pt. 1

OK, so we've got our basic jAstrologer web application that we've built in the last two exercises. You can download the project here if you haven't run through the last two exercises. Make sure you undeploy any other applications with the /jAstrologer context root that you may have already deployed to the server. So far the web application does the following:

  • Presents greeting.jsp, which uses two inputText components to ask for the user's name and birthday.
  • Saves the values entered by the user in the properties of the UserBean backing bean.
  • Reads the values of the properties from UserBean and displays them in success.jsp.

But was it really a success? In the present state, we don't know. We just take any input (or no input at all) and call it a success. That's why we need to build in a little validation to our web application. We'll start off today with some really basic stuff: making a field required and using a converter to convert the Birthday field from a String to a nice Date object.

Making a Field Required

The first thing we need to do is make sure that the user enters something for the name field. We can easily do this by using the required attribute of the inputText component.

  1. Open greeting.jsp and change the name inputText component as follows:
    	<p>Enter your name: <h:inputText value="#{UserBean.name}" 
    	        id="name" required="true"/>
    	<h:message for="name" /></p>

    What we have done is to give an ID to the name text field, so we can then specify for which component the message shows. We have then specified that the field is required, so the web application will show the error message if the user does not enter anything.

  2. Run the project and click Submit without entering a name. You get the following error:

    no name error

Using a Converter

Now we need to start treating our birthday field as a date and not just a random string. The JSF framework provides a number for converters that you can use to convert text input into object types, like booleans and so forth. In the process of converting the data, it also checks that the data is valid for the type it's converting it into. This is especially handy for our birthday input field because we can specify the date format, validate the input, and get a nice Date object all at once.

  1. Open greeting.jsp and change the birthday inputText component as follows:
            <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" 
            		id="birthday" required="true">
                <f:convertDateTime pattern="dd/MM/yyyy" />
            </h:inputText> (dd/mm/yyyy)</p>
            <h:message for="birthday" />

    What we have done is to give an id to the birthday text field, so we can then specify for which component the message shows. We have then set the converter to the pattern dd/MM/yyyy. Anything the user enters that does not match this format will cause the web application to redisplay greeting.jsp with an error message. We have also specified that the field is required, like we did with the name field.

  2. Now we need to change the type of the birthday property in UserBean.java to a Date object. Open UserBean.java and make the following changes in bold:
        private String name;
        private Date birthday;
        ...
        
        public Date getBirthday() {
            return birthday;
        }    
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }    
  3. Run the project. When you try to click Submit without entering a date, you get the following error message:

    If you enter an invalid date, you get the following error:

Friday May 19, 2006

jAstrologer JSF Tutorial - Hooking up Backing Beans

Yesterday we created a simple web application with JSF components called jAstrologer. The problem is, our web application doesn't really do anything interesting right now. In order to add rich functionality to your JSF web applications, you can associate your UI components with backing beans, or JSF managed beans whose bean properties and methods are available to the JSF components.

In our example, we'll create a UserBean managed bean that will expose two String bean properties: name and birthday.

  1. Right-click the project and choose New > File/Folder. Under the Web category, select the JSF Managed Bean template and click Next.
  2. Name the bean UserBean and put it in the astrologer.user package. Leave the rest of the settings at their default values and click Finish. The IDE opens UserBean.java in the Source Editor and adds the following bean declaration to faces-config.xml:
        <managed-bean>
            <managed-bean-name>UserBean</managed-bean-name>
            <managed-bean-class>astrologer.user.UserBean</managed-bean-class>
            <managed-bean-scope>request</managed-bean-scope>
        </managed-bean>
  3. Add the following field declarations (shown in bold) to UserBean.java:
    public class UserBean {
        
        String name;
        String birthday;
  4. Now let's generate getters and setters for the fields. Right-click anywhere in the file and choose Refactor > Encapsulate Fields. Click Next in the dialog, then Do Refactoring in the Refactoring window. The IDE switches the access level for the fields to private and creates the getter and setter methods.
  5. In greeting.jsp, make the following changes shown in bold. Note that code completion is available for UserBeans.java and its properties:
        <f:view>
            <h:form>
                <p>Enter your name: <h:inputText value="#{UserBean.name}" /></p>
                <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" /></p>
                <h:commandButton value="Submit" action="submit" />
            </h:form>
        </f:view>
  6. Add the JSF taglib declarations to success.jsp. You can copy and paste them from greeting.jsp.
  7. Add a JSF form to success.jsp by clicking the JSF Form button in the Palette window and releasing it below the h1 tag in the Source Editor.
  8. Make the following changes to success.jsp:
        <h1>Congratulations</h1>
        <f:view>
            <h:form>
                <p>You've successfully registered with jAstrologer.</p>
                <p>Your name is <h:outputText value="#{UserBean.name}" /></p>
                <p>Your birthday is <h:outputText value="#{UserBean.birthday}" /></p>
            </h:form>
        </f:view>
  9. Right-click the project and choose Run Project. The same greeting.jsp page greets you when the application is deployed.

    greeting.jsp

    When you enter values and click Submit, success.jsp also displays the values you entered, as shown in the following diagram:

    result.jsp

Thursday May 18, 2006

Learn JSF with jAstrologer

I'm working on a new series of tutorials for JSF in NetBeans IDE. We're going to put together an application called jAstrologer, which will take your name and birthday, query a database, call a web service, and spit out:

  • Your zodiac sign
  • Your birthstone
  • The chinese year you were born in
  • A daily horoscope

The first thing is - I hate the name. Anybody out there have a better name? Is there a famous astrologer that we could name this after? A quick search on Wikipedia brings up a certain Guido Bonatti from Forli (which happens to be the arch-nemesis of my town in Italy, Ravenna. Something like Springfield and Shelbyville in the Simpsons.) But I'm not sure about calling it BonattiVision or something.

But I digress... Here's the basic outline of what we want to cover in the series of articles:

  • Getting Started
    • Creating project
    • Creating JSP and declaring taglibs
    • Adding view and form tags
    • Basic navigation
    • Backing bean with simple operation
  • Validating Data and Showing Error Messages
    • Making the birthday field convert to a date, checking for valid entry
    • Checking that the birthday is in the past, not the future
    • Showing error messages for above validation
  • Querying a Database
    • Create an action to take the info, validate, and query db for astrological data
    • Showing data from a data source
  • Localizing and Formatting
    • Extract all display text to properties files
    • Using a CSS to do better formatting
  • Adding Custom Components
    • Incorporating Tomahawk components (inputDate for the date)
    • Setting up the shared libraries on the server
  • Web Service Integration

If anyone has any ideas about things that aren't covered, etc., let me know. So let's just right in and get started. Flash video coming soon.

Getting Started

First we're going to create the simplest web applicaiton possible. We'll just have one JSP page that asks for a name and birthday, then a success page that displays a success page. We'll have the web application display the success page no matter what the user writes in the fields, just to keep things simple.

Creating the Web Application

  1. Create a new Web Application project called jAstronomer. On the third page of the New Web Application wizard, choose to add the Java Server Faces project and leave the rest of the information at its default. Create the project.

Creating the Greeting Page

The IDE creates the web application with a default index.jsp and a welcomeJSF.jsp page. We'll ignore both of these pages and create our own greeting page.

  1. Rright-click the project node and choose New > JSP, name the file greeting, and click Finish.
  2. Now we need to declare the JSF tag libraries in the JSF file. Change the following code:
    <%--
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
    --%>

    To the following:

    <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
    <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>

    Notice that you can use the code completion to help put in not just the tag name and attributes, but also the URIs of the tab libraries.

  3. Change the contents of both the title and h1 tags to Welcome to jAstrologer.
  4. Now let's add a JSF form to the file. In the Palette, click the JSF Form button, drag it to below the h1 tag, and release. In the dialog box, leave Empty Form selected and click OK. The IDE fills in the following code in bold:
        <h1>Welcome to jAstrologer</h1>
        
        <f:view>
            <h:form>
            </h:form>
        </f:view>
    
        </body>
  5. We are going to use inputText components to get the user input and a commandButton component to submit the form. In the Source Editor, change the contents of the h:form element to the following:
        <f:view>
            <h:form>
                <p>Enter your name: <h:inputText value="name" /></p>
                <p>Enter your birthday: <h:inputText value="birthday" /></p>
                <h:commandButton value="Submit" action="submit" />
            </h:form>
        </f:view>

Creating the Success Page

Now we're going to create a page that simply says congratulations.

  1. Create a new JSP file as described below. Name the file success.
  2. Change the contents of the file to the following:
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Congratulations</title>
        </head>
        <body>
    
        <h1>Congratulations</h1>
        
        <p>You've successfully registered with jAstrologer.</p>
        
        </body>
    </html>

    Notice that we're just using straight HTML here, so there's no need to declare the JSF tag libraries yet.

Setting Page Navigation

Page navigation in JSF is controlled by the faces-config.xml file, which is located under the Configuration Files node in the Projects window. For each page you set up a navigation rule which contains one or more navigation cases. Like we said above, we're just going to map the submit action from the commandButton to success.jsp, no matter what the user enters in the fields.

  1. Double-click faces-config.xml to open the file in the Source Editor.
  2. Right-click anywhere in the file and choose Java ServerFaces > Add Navigation Rule. Type /greeting.jsp in the Rule from view field and optionally enter a description of the rule.

    The following code is enterd in faces-config.xml:

        <navigation-rule>
            <description>
                handle user input
            </description>
            <from-view-id>/greeting.jsp</from-view-id>
        </navigation-rule>
  3. Right-click inside faces-config.xml and choose Java ServerFaces > Add Navigation Case. Set the following:
    • From View: /greeting.jsp
    • From Outcome: submit
    • To View: /success.jsp

    add navigation case dialog

    Click OK. The IDE enters the following code in faces-config.xml:

        <navigation-rule>
            <description>
                handle user input
            </description>
            <from-view-id>/greeting.jsp</from-view-id>
            <navigation-case>
                <from-outcome>submit</from-outcome>
                <to-view-id>/success.jsp</to-view-id>
            </navigation-case>
        </navigation-rule>

Configuring and Running the Application

Now let's set the IDE to display greeting.jsp when it runs the application and, finally, test out the application.

  1. Right-click the project and choose Properties.
  2. Click the Run node and type /faces/greeting.jsp in the Relative URL field. Then click OK.
  3. Right-click the project and choose Run. The IDE builds the project, starts the application server, deploys the application, and shows the following page in the external browser:

    greeting.jsp

    When you click the Submit button, you see the following:

    success.jsp

So that's it for the very basic intro. Not rocket science, I know. But we've got the basics down and tomorrow we'll start doing more interesting stuff, like hooking it up to a backing bean and so forth. So stay tuned.

Wednesday May 17, 2006

Using Hibernate as the Persistence Manager on GlassFish

There's been a lot of talk about using Java Persistence API to plug in Hibernate as the persistence manager instead of Oracle's toplink, so let's take a look at how you do this. First, you download the Hibernate Core 3.2.0 cr2 and Hibernate EntityManager 3.2.0 cr1 from the Hibernate website.

Then you copy over the correct JAR files from hibernate to the GlassFish lib directory. I can't figure out exactly which JAR files to copy so I copied hibernate3.jar, hibernate-entitymanager.jar, then all of the JAR files in each of hibernate-3.2/lib and hibernate-entitymanager/lib. I tried to read the READMEs in the lib folders to figure out which ones were really required but I was obviously leaving something out because my App Server wasn't starting correctly. If anyone out there knows which JAR files are strictly required please let me know.

Of couse, restart the server if it's already started.

Now start up the IDE and start the Java DB database. Create a web application project (in this case HibernateApp) and add the JSF framework to it in the second page of the New Project wizard. Right-click the project node and choose New > Entity Classes from Database. Set the jdbc/sample database as the Data Source, select the CUSTOMER table (this is an example table shipped with the IDE) and click Next.

Now it's time to create the persistence unit by clicking the Create Persistence Unit button. There's still some bugs that need to be worked out. In the final version the IDE will scan your GlassFish dir and list Hibernate in the Persistence Provider drop-down. For now, you have to create the persistence unit with TopLink and then manually change it in the persistence unit XML. Let's do that now. Set hibernate as the persistence unit name, leave TopLink as the persistence provider, and switch the table generation strategy to None. You have to do the final one because the syntax for the XML generated by TopLink and Hibernate are different.

When you click Finish, our persistence unit is created (persistence.xml under Configuration Files node) and the entity classes are created (under Source Packages). Double-click persistence.xml and swith to the XML view (click the XML button at the top of the editor). Change the provider element to org.hibernate.ejb.HibernatePersistence, as shown below:

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="hibernate" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<properties/>
</persistence-unit>
</persistence>

Now we can quickly generate JSF pages for the entity classes with Geertjan's favorite feature. Right-click the project node and choose New > JSF Pages from Entity Class. Add both Customer.java and DiscountCode.java to the list of selected classes and click Next. Change the package to hibernatesample.controller and click Finish (we won't specifiy a special folder for JSF pages).

And just Run the project. Hopefully it'll work. It didn't for me the first time, I got a 500 error. I restarted the server again and tried again and everything seemed to work. I guess GlassFish didn't register all of the Hibernate libraries first.

OK, now time to show my ignorance. Why would you want to do this? I mean, is it just a matter of personal preference? Is there a performance difference between TopLink and Hibernate? Any illumination you can shed on this would be helpful.

About

johnc

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today