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

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…

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?

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.

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.

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

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.