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.
¬† ¬† ¬† ¬† ¬† ¬† 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,


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