Home > Blockchain >  Why is the Java Persistence API generating ids based on the total amount of entities?
Why is the Java Persistence API generating ids based on the total amount of entities?

Time:11-20

I am building a Web API that calculates a loan. This loan has a list of payments:

@Entity
public class Loan {
    
    @Id
    @GeneratedValue
    @Column(name = "id", nullable = false)
    private Long id;

    ...

    @OneToMany(cascade = CascadeType.ALL)
    private List<Payment> amortizationSchedule;

}


@Entity
public class Payment {
    @Id
    @GeneratedValue
    private Long id;

   ...

}

Whenever I store these entities I would expect the primary keys to be generated as follows:

  1. Loan created, generated id = 1
  2. Loan created, generated id = 2
  3. Payment created, generated id = 1
  4. Payment created, generated id = 2

Instead the following happens:

  1. Loan created, generated id = 1
  2. Loan created, generated id = 2
  3. Payment created, generated id = 3
  4. Payment created, generated id = 4

Why is this happening? And how can I get the Java Persistence API to base the primary key generation on the amount of entities of a certain class instead of the total amount of entities?

CodePudding user response:

Try adding a strategy to your generationvalue

@GeneratedValue(strategy = GenerationType.IDENTITY) 

CodePudding user response:

The default @GeneratedValue in Hibernate is AUTO, but since hibernate 5 the default interpretation of AUTO has changed and is using a sequence generator. This is why you were seeing consecutive number for different tables, because the ids came from the same source, a sequence (and if you are using MySQL, and I suspect you do, which doesn't support SEQUENCE, you would notice that hibernate had created a table hibernate_sequence to emulate it).

https://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators-auto

This is the default strategy since Hibernate 5.0. [...] . When using this strategy, AUTO always resolves to SequenceStyleGenerator. If the underlying database supports sequences, then a SEQUENCE generator is used. Otherwise, a TABLE generator is going to be used instead.

To fix this just do what @CodeAddict said in his answer, use @GeneratedValue(strategy = GenerationType.IDENTITY) so it uses the AUTO_INCREMENT feature of MySQL.

  • Related