jakartaee / jakartaee/persistence

Sharing a single version field between multiple entities

Open
#92 6 comments 3 reactions 0 assignees View on GitHub
Priority: Minor Type: Improvement
Dominant language
Java
Stars
268
Forks
78
Avg merge
1d 6h
Merged PRs (30d)
13

Description

I have been using Hibernate then JPA for almost 10 years and there is one feature that I miss and would like to be discussed by the EG.

Currently, in JPA, with a typical (bi-directional & mapped) Parent-Child relationship, the parent gets versioned when a child is added or removed from the parent collection.

I would like to know if it is possible to version the parent when a child is updated without artificially updating a dummy property on the parent (let's say lastModificationDate).

I'd like to do that to preserve an objects' graph coherence (invariants).

example:

I have the following entities:

```
[Order] 1 --- * [OrderLine (quantity)] * --- 1 [Product (price)]
```

and have a rule (at the order level that can be implemented with javax.validation) that the total amount for an order (= sum quantity * price for each line) must not be greater than $5000\.

If two users concurrently modify the same order by changing the quantity of 2 different lines, the last one committing won't see the changes made by the first one (even if each OrderLine has a @Version property) and won't be able to enforce the invariants on the parent order.

However, if the order itself is versioned at each commit (even if none of its direct property has changed but one of its children has been modified), the last one committing will get an OptimisticLockException (and the order won't be corrupted).

Therefore, I would like to be able to specify something like this:

```java
@Entity
class Order {

@Id
Long id;

@Version
Integer version;

@OneToMany(cascade = ..., mappedBy = "order")
Set lines;
}

@Entity
class OrderLine {

@Id
Long id;

@ManyToOne
@Version // if this orderLine changes, bump the version of the whole order
Order order;
}
```

That way, I could have a single version field for a graph of objects. Speaking with Domain-Driven Design in mind, this would result in having a version field only on the aggregate root.

What do you think?

Contributor guide

Open the contributing guide

Research direction

Start with the Order, OrderLine, and Product example in the issue and review how JPA @Version currently handles entity and relationship changes. Determine whether sharing a version across the aggregate graph is supported or requires a specification change, then document the resulting behavior and concurrency implications for the proposed invariant.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
database
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.