Thursday Dec 18, 2014

Point of Clarification: NetBeans, JSF, and MySQL Primary Keys

Recently I was working on a project using JavaServer Faces with a MySQL backend (Yes, I jump around a lot! Or as I like to say, I go where the voices in my head tell me to go.). :) While discussing the project with another dev there, I referenced an earlier post I had written about a small "gotcha" I'd encountered with the code NetBeans generates as a first-cut for JSF CRUD apps.

NetBeans does a great job producing a framework that you can build upon for many (many many) types of apps. The issue I'd found was small and easily resolved, and I covered the quick fix needed to make it work...but in hindsight, I didn't explain it very well.

The annotation required for MySQL's AUTO_INCREMENT of primary key values is the important bit from MySQL's perspective. But in order to get to MySQL in the first place, I added the line setting the object's "id" to 0 (in my example). This wasn't due to MySQL per se; it was a requirement levied by the @NotNull annotation for our @Entity class's id member variable. Once the bean validation took place, the object/values could be persisted.

For anyone who may have been a bit fuzzy on the "why", I hope this helps. :)

Keep coding,

Sunday Mar 25, 2012

NetBeans, JSF, and MySQL Primary Keys using AUTO_INCREMENT

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.




            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,


UPDATE: Please see this follow-on article for a bit of clarification with regard to "why". Hint: It has to do with bean validation... ;) 


The Java Jungle addresses all things Java (of course!) and any other useful and interesting tools & platforms that help us GET IT DONE. "Artists ship," after all. :)

Your Java Jungle guide is Mark Heckler, a Software Architect/ Engineer and Oracle Developer Evangelist with development experience in numerous environments. Mark's current pursuits and passions all revolve around Java, the Cloud, & the IoT, and leave little time to blog or tweet - but somehow, he finds time to do both anyway.

Mark lives with his very understanding wife in the St. Louis, MO area.

Stay Connected


« November 2015