Issue
Here is how Id is configured in my entity class,
@Entity
@Table(name = "test_data")
@NamedQuery(name = "TestData.findAll", query = "SELECT t FROM TestData t")
public class TestData implements Serializable {
@GenericGenerator(name = "testDataSequenceGenerator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = {
@Parameter(name = "sequence_name", value = "test_data_Seq"),
@Parameter(name = "initial_value", value = "1000"), @Parameter(name = "increment_size", value = "1") })
@Id
@GeneratedValue(generator = "testDataSequenceGenerator")
protected Long id;
}
I persist data into the table implementing JpaRepository interface. The incrementing worked fine until I developed a new biz solution where I would need to insert the ID value based on biz needs.
Example: My current top row in Postgres DB is having ID = 1000. Therefore my next would be 1001 as per the generation config I have done in my entity. But with the new enhancement. I am inserting ID = 2000. Since JPA would not allow user-defined ID (I believe it is because of the configuration on ID), I have used native query to execute the same using the EntityManager.
Now doing this; once I run biz workflow that inserts ID based on user input. And later when I am trying to create a new entry, hibernate is incrementing by using the previously created ID,i.e, 1001, instead of 2001.
Is this because of any caching in hibernate? Do I need to update the next value in hibernate. Could you please assist me here?
Solution
According to your configuration, you're using a sequence to generate ids (test_data_seq
) without using hibernate sequence value cache. As you set ID = 2000 manually, the sequence's current value isn't being updated. You need to update it manually, e.g. by using this function:
SELECT setval('test_data_seq', 2000);
In this case, the next generated value should be 2001.
Overall, it's better to avoid setting ids manually if you use sequence generators for it, because there is a high risk to have a collision.
Answered By - amseager