How to generate primary keys with JPA and Hibernate

preview_player
Показать описание
Today, I will show you how to generate unique primary key values with JPA and Hibernate.
But before we start, I want to know how you get the primary key values in your application? Do you use natural keys or UUIDs or do you generate technical IDs?
Please post a comment below and tell me about it.

I prefer to generate simple, numerical, technical IDs like you can see in the following code snippet instead of using natural keys which often require the combination of multiple attributes.
Technical IDs are easier to manage and all involved systems, mainly the database and Hibernate, can index them very efficiently. This allows you to focus on the business logic of your application and avoids performance issues.

If you like this video, please give me your thumbs up and share it with your friends and co-workers.

Like my channel? Subscribe!

Join the free Member Library:

Want to connect with me?
Рекомендации по теме
Комментарии
Автор

We need to take extra care with Sequence of Oracle DB.
In my recent project, I was working with Oracle database. I chose the GenerationType.SEQUENCE, but ran into issues. I was having OneToMany relationships so whenever there were 20+ child records, I was getting EntiytExistException. The issue I found was that the Oracle Sequence was not in sync with Hiberanate caching(allocationSize). The allocationSize I kept was 20 and the Sequence INCREMENTBY = 1.
So suppose if the sequence returned 10, Hibernate generates 10 to 29 in the cache(based on allocationSize). So when those Ids got consumed, Hibernate ask Oracle Sequence to return next value, and this time it returns 11(INCREMENTBY=1). Hibernate tries to use 11 as Id and stuck as EntityExistException, because 11 was already generated and used by Hibernate in its cache.
So for the resolution to this, I had to kept the INCREMENTBY = allocationSize. This resolved the issue.
Is it the expected behaviour with Oracle, or I missed something?

puspendertanwar
Автор

Thanks. Very simple and easy to understand with your explanation.

LakshmananMe
Автор

I want to create BaseEntity class where it will be id too which will extend all entities. But in my DB app, there is tablename_id. How can make that?

Gorky
Автор

Why are there 3 selects from the sequence before the 20 inserts?

christianweise
Автор

as for the question. It really depends. if the system i work on already has an opinion on how to generate a key, i just go with what the system does unless i can give a really good reason not to.

if i am making the decision, i first try to figure out what context my code will run in. if i am to use the data for batch jobs, i usually go with the smallest key practical. if many users need to create instances simultaniously, i would prefer UIIDs with some colision handling.

Gunsong
Автор

Thanks for your video. Can you please suggest which generation strategy suitable for below use case. Use Case: I am using Hibernate 5 + with latest spring boot 2.0. Backend is Oracle 12c. Based on my understanding, Oracle 12c has auto increment identity feature. In this case, Can I use Generation strategy as Identity or I have to create sequence in Oracle use it. Moreover, It requires to support Batch processing as well. I believe Identity won't support it and sequence does. Please suggest the right way of doing. Thanks.

baskararumugam
Автор

Great video, I have a doubt. If I need to keep the order of the id, I mean no spaces between each récord, what's the most properly option?

rsnivelo
Автор

I generate primary key using before insert trigger. Is there any way to use it in hibernate when I insert a new row? It throws exception because of the null value in @Id field of the entity

valijonsobirov
Автор

If we are using sequence generator type, then primary key column in database must not be IDENTITY, Right??

Can We take advantage of jdbc batch by using Auto generation strategy??

yatishsonkeshariya
Автор

@6:00 Your example with allocationSize=10 makes three calls to `next_val` sequence generator. I didn't understand why this is the case, would you mind explaining how the 10 relates to the 3 calls please? (or maybe i misunderstood and they're not connected).

MariusSemeonOrtiz
Автор

I have a question goes like this:
I have 3 columns, (id), first_name, last name.
I have made column as non null and generated.
i am running in a simple program (no spring, etc ==> plain old java : POJO) :)
but if run the program twice, i get duplicate rows with different ids (incremented automatically)

how do i avoid this?

P.S. ==> I know this is not stackoverflow but hey....any platform is an stackoverflow if you're eager enough to learn and a bit baffled!
P.S.2 ==> I am obviously new to this.

would appreciate some advice on how to resolve this :D

P.S.3 I have done something like this with JDBC ("01" + String.valueOf(field) + "02" +
select everything from db, and only insert the ones that are rejected by the inner join
---> join condition relies on equality of the long string value made from concatenating the string values of the fields

alcapone
Автор

I want to use pk as string .is it possible in JPA?

ajaydangi
Автор

I am using SEQUENCE, but still facing EntityExistsException exception.
@Id
@SequenceGenerator(name = "SequenceLocIdGenerator", sequenceName = "LINE_LOCQTY_JPA_ID_SQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SequenceLocIdGenerator")

private Long lineLocqtyJPAId;

And when I use this sequence, I get the below logs:

Hibernate:
select

from
dual
Hibernate:
select

from
dual
A different object with the same identifier value was already associated with the session :

Any clue what could be the issue, as even I am using SEQUENCE for generating ID, hibernate is complaining for ID.

puspendertanwar
Автор

Technical IDs, always. There are no reasons for natural keys and rare reasons for UUIDs.

arnelewinski