jakartaee / jakartaee/persistence

primitive ids when database primary key is 0

Open
#885 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
268
Forks
78
Avg merge
1d 6h
Merged PRs (30d)
13

Description

I have encountered this problem and maybe it is an incompleteness in the specification. But if you create a new entity object with a primitive @ Id field, which is allowed, and there is a record in the database with the value 0 then this new entity object is not new/transient. But it is also not really detached because if you merge it then it is now implementation specific what happens. EclipseLink and Hibernate have properties to allow 0 as an record identifier. The things are also odd if you read this record from the database and write it back after a modification. Hibernate AFAIR assignes a new value to the id field and inserts it, and you end up with a duplicate. But if you allow 0 as an identifier then you cannot use primitive key identifiers anymore because they cannot become NULL. And it somehow contradicts the option to have primitive types as primary key identifiers.

OK, i do not know how often this problem occurs in real life projects. We _fixed_ it by reassigning a different number for the primary key and updated all foreign keys. But we had it and since the ORM implementations have some options to deal with it, it seems, that it is not so uncommon.

I also thought about a fix for it. And i ended up with an additional field in the @GeneratedValue annotation:

```java
long generatorActivationValue() default 0L;
```

The usage would be:

```java
@Id
@Column(name = "my_id")
@GeneratedValue(strategy = SEQUENCE, generator = "seq_gen", generatorActivationValue = -1L)
private long id = -1L;
```

In this case an entity object with the primary key identifier value "-1L" would be considered as new/transient and the id generator would generate a new value for the primary key identifier. Because the value "-1L" would be a trigger value for the id generator. This solution also shouldn't have any backwards compatibility issues.

Contributor guide

Open the contributing guide

Research direction

Start by reviewing the @Id and @GeneratedValue specification sections covering primitive identifiers, transient entities, merging, and generated values. Determine whether the proposed generatorActivationValue behavior can be specified consistently across providers; done would require an agreed API or specification change plus compatibility coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend-api-design, databases
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.