How to generate primary keys with JPA and Hibernate

Поделиться
HTML-код
  • Опубликовано: 29 янв 2025

Комментарии • 28

  • @Gorky25
    @Gorky25 2 года назад +1

    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?

  • @puspendertanwar9378
    @puspendertanwar9378 7 лет назад +5

    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?

  • @MariusSemeonOrtiz
    @MariusSemeonOrtiz 2 года назад

    @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).

  • @LakshmananMe
    @LakshmananMe 6 лет назад

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

  • @abhishekdanej
    @abhishekdanej 6 лет назад

    Very clear and precise! thanks!

  • @valijonsobirov6738
    @valijonsobirov6738 5 лет назад

    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

  • @baskararumugam8107
    @baskararumugam8107 5 лет назад

    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.

  • @christianweise8806
    @christianweise8806 2 года назад

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

  • @Gunsong1
    @Gunsong1 3 года назад

    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.

  • @yatishsonkeshariya4958
    @yatishsonkeshariya4958 4 года назад

    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??

  • @mohamedjammal9049
    @mohamedjammal9049 6 лет назад

    Thank you very much!

  • @rsnivelo
    @rsnivelo 7 лет назад

    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?

  • @ajaydangi582
    @ajaydangi582 6 лет назад

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

    • @Thorben-Janssen
      @Thorben-Janssen  6 лет назад

      Yes, you just need to annotate an attribute of type String with the @Id annotation

    • @ajaydangi582
      @ajaydangi582 6 лет назад

      thanks to reply but it doesn't work. not create table in mysql.

  • @alcapone1366
    @alcapone1366 4 года назад

    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

  • @puspendertanwar9378
    @puspendertanwar9378 7 лет назад +1

    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")
    @Column(name="LINE_LOCQTY_JPA_ID")
    private Long lineLocqtyJPAId;
    And when I use this sequence, I get the below logs:
    Hibernate:
    select
    saurabh.LINE_LOCQTY_JPA_ID_SQ.nextval
    from
    dual
    Hibernate:
    select
    saurabh.LINE_LOCQTY_JPA_ID_SQ.nextval
    from
    dual
    javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.bcone.oracle.ebs.model.XxspPoInLineLocqty#68]
    Any clue what could be the issue, as even I am using SEQUENCE for generating ID, hibernate is complaining for ID.

    • @Thorben-Janssen
      @Thorben-Janssen  7 лет назад

      The annotations seem to be ok.
      Do you set any ideas manually?
      Do you try to persist the same entity multiple times?

    • @puspendertanwar9378
      @puspendertanwar9378 7 лет назад

      Hi Thorben, I have raised the complete details for question on
      stackoverflow.com/questions/48020829/javax-persistence-entityexistsexception-with-sequencegenerator.
      It would be great help if you could have a look.
      Thanks

  • @arnelewinski79
    @arnelewinski79 4 года назад

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

    • @Thorben-Janssen
      @Thorben-Janssen  4 года назад

      I agree in most cases.
      Sometimes, you have an obvious natural key. So, why not use it. But that happens very rarely.
      UUIDs can be a good solution for distributed applications or microservices that exchange and aggregate data.

    • @arnelewinski79
      @arnelewinski79 4 года назад

      @@Thorben-Janssen An obvious primary Key is never as good as a definite primary key. UUID can be substituted by Class and ID as a definite primary key in distributed Systems.

  • @ahmadhosny00
    @ahmadhosny00 7 лет назад

    We use technical, numerical IDs.

    • @Thorben-Janssen
      @Thorben-Janssen  7 лет назад +1

      I do the same in most of my projects. As I said in the video, that's almost always the fastest and easiest option

  • @wiliamferraciolli5380
    @wiliamferraciolli5380 4 года назад

    UUID