How to map a composite identifier using an automatically @GeneratedValue with JPA and Hibernate

#1

In today’s modern SAAS applications the database usually contains composite key as the primary key as one of the strategies of multitenancy is to have a tenant column in all tables.
Hence the natural way of choosing a primary key is to create a composite key consisting of [tenant column] + [id] column.
Choosing the ID column as autogenerated is a preferable and safe way to make sure the primary keys are generated at the database level.
In this scenario, the Hibernate Fails however we can achieve this feature in other ORM (EclipseLink etc.) with some custom defined annotations.

Here is a link with an example of this issue.

Now, When we evaluate what is the best ORM to choose for the product, Every time I conclude with hibernate as it checks all boxes, But just because of this deficiency we have to go with some other ORMs.

I’ve found some older links about this issue as well (https://forum.hibernate.org/viewtopic.php?f=1&t=1006818),
It’s pretty strange why hibernate community has not addressed this yet.
Hoping this feature would land in Hibernate 6 or in future…

0 Likes

#2

In this scenario, the Hibernate Fails however we can achieve this feature in other ORM (EclipseLink etc.) with some custom defined annotations.

No, it does not fail. In fact, that article that you linked already provide a way to make it work with Hibernate.

It works just fine for SQL Server too, so I’m not sure why you said it was not working.

But just because of this deficiency we have to go with some other ORMs.

What deficiency?

I’ve found some older links about this issue as well.

That’s a 9-year-old question. As long as you don’t want to use a Hibernate version that dates back to 2010, you are fine.

It’s pretty strange why hibernate community has not addressed this yet. Hoping this feature would land in Hibernate 6 or in future.

Why wait for Hibernate 6 when you have it working on Hibernate 5 too?

0 Likes

#3

Hello Vlad,
Thanks for the reply, But this approach involves adding a noninsertable column and specifying @SQLInsert annotation on every entity.
There should be a natural way to do this thing. I mean we should only specify the Embedded key and autogenerated field in the embedded key and use this embedded key in the Entities as we deal with normal ID keys.

0 Likes

#4

You can use a database sequence and the @IdClass solution and you won’t need to override the @SQLInsert.

That’s as natural as you can get.

0 Likes

#5

Not all database support sequence and existing databases where every table has identity objects defined then the only way to do is using @SQLInserts.

0 Likes

#6

Actually, only MySQL does not support sequences. Oracle, SQL Server, PostgreSQL and MariaDB support sequences, and they are preferred to IDENTITY because they allow automatic JDBC batch inserts.

0 Likes