First8 staat voor vakmanschap. Al onze collega’s zijn een groot aanhanger van Open Source en in het bijzonder het Java-platform. Wij zijn gespecialiseerd in het pragmatisch ontwikkelen van bedrijfskritische Java toepassingen waarbij integratie van systemen, hoge eisen aan beveiliging en veel transacties een belangrijke rol spelen. Op deze pagina vind je onze blogs.

GORM map table without primary key

Used versions: GORM 6.1.9 

Hibernate 5.1.5

Grails 3.3.10

This week I had to map an object on an existing database table with an existing primary key not named ‘id’ but ‘aniId’. By convention GORM is expecting such an ‘id’ property and if it is absent GORM inserts it for us which is very handy with new tables. But with an existing table this is not what you want GORM to do, because eventually the database will throw a SQL error for this unknown column.

GORM is the acronym for Groovy Object Relational Mapping. It is build upon Hibernate. GORM provides us a nice interface for defining domain objects such as shown below. Hibernate is performing the actual mapping of the domain object on a database table by generating sql-queries.

The issue

Given the following domain class (Groovy) which maps to a table ‘ANIMAL’ with aniId as primary key:

When we try to find an Animal

GORM is inserting the ‘id’ property automatically which causes Hibernate to add ‘id’ to the sql-query:

Which obviously raises an error:

ERROR — [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00904: “THIS_”.”ID”: invalid identifier

The solution

Add an ‘id’ property for GORM to use it and prevent Hibernate from using it in the query by marking it ‘transient’. Point the ‘id’ property to the real identifier ‘aniId’

Add a list with transients

And, most important, in static mapping add a mapping for id onto the real primary key

Now the query is generated correctly and executed successfully: