Hecklers in Development
Code, coffee, & camaraderie. Collection, unordered. ;)

Cross-posted from The Java Jungle by Mark

I recently had the opportunity to spin up a small web application using JSF and MySQL. Having developed JSF apps with Oracle Database back-ends before and possessing some small familiarity with MySQL (sans JSF), I thought this would be a cakewalk. Things did go pretty smoothly…but there was one little “gotcha” that took more time than the few seconds it really warranted.

The Problem

Every DBMS has its own way of automatically generating primary keys, and each has its pros and cons. For the Oracle Database, you use a sequence and point your Java classes to it using annotations that look something like this:

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator=”POC_ID_SEQ”)
@SequenceGenerator(name=”POC_ID_SEQ”, sequenceName=”POC_ID_SEQ”, allocationSize=1)

Between creating the actual sequence in the database and making sure you have your annotations right (watch those typos!), it seems a bit cumbersome. But it typically “just works”, without fuss.

Enter MySQL. Designating an integer-based field as PRIMARY KEY and using the keyword AUTO_INCREMENT makes the same task seem much simpler. And it is, mostly. But while NetBeans cranks out a superb “first cut” for a basic JSF CRUD app, there are a couple of small things you’ll need to bring to the mix in order to be able to actually (C)reate records. The (RUD) performs fine out of the gate.

The Solution

Omitting all design considerations and activity (!), here is the basic sequence of events I followed to create, then resolve, the JSF/MySQL “Primary Key Perfect Storm”:

  1. Fire up NetBeans.
  2. Create JSF project.
  3. Create Entity Classes from Database.
  4. Create JSF Pages from Entity Classes.
  5. Test run. Try to create record and hit error.

It’s a simple fix, but one that was fun to find in its completeness. 🙂 Even though you’ve told it what to do for a primary key, a MySQL table requires a gentle nudge to actually generate that new key value. Two things are needed to make the magic happen.

First, you need to ensure the following annotation is in place in your Java entity classes:

@GeneratedValue(strategy = GenerationType.IDENTITY)

All well and good, but the real key is this: in your controller class(es), you’ll have a create() function that looks something like this, minus the comment line and the setId() call in bold red type:

    public String create() {
        try {
            // Assign 0 to ID for MySQL to properly auto_increment the primary key.
            current.setId(0);
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle(“/Bundle”).getString(“CategoryCreated”));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle(“/Bundle”).getString(“PersistenceErrorOccured”));
            return null;
        }
    }

Setting the current object’s primary key attribute to zero (0) prior to saving it tells MySQL to get the next available value and assign it to that record’s key field. Short and simple…but not inherently obvious if you’ve never used that particular combination of NetBeans/JSF/MySQL before. Hope this helps!

All the best,
Mark

Share

Related Posts:


Tags: , , , , , , , ,

I recently ran across a neat concept that I’d really like to see spring up in more places. I’m not sure how to accomplish that exactly, but it does have me thinking.

The Seneca College Linux Club created a kiosk where folks can walk up, select a Free/Open Source Software package, and burn it to a CD or DVD that they bring with them. Based upon the FreedomToaster project in South Africa, this spreads high-quality software throughout the community with very little effort and no real cost (blank CDs and DVDs are typically a few cents apiece). All boats rise with the tide, and this is a huge positive for everyone.

What about commercial software vendors, you may ask? Well, the more people use quality software, the more their use of technology and software increases overall. In short, the more they can do, the more they want to do. Quality commercial software fills gaps, races ahead, provides depth of support, and offers profit opportunities – it’s always been that way and will likely never change. The growth of the software industry often pits commercial against FOSS, but that doesn’t mean that there isn’t room for both.  🙂

Click here to read about the Seneca College Freedom Toaster and see what you think. Ready to start building?

K

Share

Related Posts:

  • Please check back for related posts!

Tags: , , , , , , ,

Powered by Wordpress
Theme © 2005 - 2009 FrederikM.de, heavily modified by Mark Heckler
BlueMod is a modification of the blueblog_DE Theme by Oliver Wunder