Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate generates negative id after a certain amount of insert

I have a weird behavior of Hibernate (3.6.1.Final) in my application and I am pretty desperate at the moment. The behavior occurs on both MariaDB 10.1 and RDS on Amazon.

After a certain amount of successful persists (always around ~5k) Hibernate fires a:

SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

From what I see in the stacktrace Hibernate tries to fill a foreign key in a entity with a negative value that violates the FK constraint (the target table of the FK does not have such primary key value).

The strange thing is:

  • It happens only after around ~5k successful persists
  • After submitting such number of persist operation, the error occurs even if I restart the application (as well as the DB). Only solution is to wipe out the DB and repeat.
  • The error occurs independently from the load (continuous, in batches, single or multithread).

The following is the FK of the entity that is violated during the insert:

    @Entity
    @Cacheable
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class Charge extends Entry {

        @OneToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "totalId")
        private Amount total;
     //....

And this is how the primary key is defined in the Amount entity:

     @GeneratedValue
     @Id
     @Column(nullable = false)
     private Integer pk;
     //....

My questions are:

  • Why a non-valid negative value occurs in the FK ? (the primary key targeted by the FK is set as auto increment, starting from one and all the preceeding inserts worked perfectly accordingly to this)
  • Why does the error occurs only after ~5k persists ?
  • Why not even a restart of the application fix the problem? DB is fine because a manual insert outside the application works (with valid FK values)

My suspicion is Hibernate and how it manages the auto_increment on the DB. The are many posts on the topic but none of them fit my specific case (error occurring only after a certain usage).

Last note: On the DB auto_increment is initially set to 1. All the initial persists (before the error appears) of the Amount entity have a incremental PK that start by 1: (1,2,3, ...). So again why after a while Hibernate comes up with a negative (incompatible to the FK)?

Thank you so much in advance for your help.

Best G.

like image 415
user2248614 Avatar asked Dec 07 '25 03:12

user2248614


1 Answers

Maybe is the limite of type int ?

Try this :

@Id
@GeneratedValue (strategy = GenerationType.AUTO)
@Column (name = "id")
private long id;
like image 115
Yiao SUN Avatar answered Dec 08 '25 15:12

Yiao SUN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!