Dysfunctional @Enumerated Annotations in Hibernate

NixMash

WordPress Site Management for Small Business

Home

Search

Tags

Services

Contact Me

I often like to set a mapped Entity Model property as an Enumerator type. The new Links feature we’re building in NixMash Spring (more on that as it happens) uses a PostDisplayType enumerator.

We’ll assign it on the Post entity displayType field like so.

Now we can save it to our database table VARCHAR(20) field as a String yet enjoy coding with its Enumerator properties in Java.

But instead of saving Strings to the database, the PostDisplayType ORDINAL value is being saved!

The Javax.Persistence @Access annotation is used to specify an access type to be applied to an entity class for mapping purposes. (Getting deeper into @Access , it can also be applied to fields, but that’s “outside the scope of this post” as they say.) Its values are FIELD and PROPERTY . If not explicitly noted it defaults to whichever type of element assigned to the @Id value.

Our Model Class Signature:

See the problem? Our @Access type is PROPERTY ( getDisplayType() , or on the getter methods.) But as we saw earlier, our @Enumerated annotation is on a FIELD .

We’re in trouble here with more than just our @Enumerated annotation, but let’s hypothetically say that the @Column is defined properly with our getter and we add @Enumerated to the field just for kicks. The result is that Hiberate ignores our @Enumerated settings and ordinals end up in our database.

The moral of the story is to define the mapped @Enumerated element with the correct FIELD/PROPERTY @Access setting for the class, and if not explicitly set, on the same element type as your @Id field.

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.