spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.61k stars 38.13k forks source link

Consider allowing attributes annotated with CreatedDate to determine "isNew" status for R2DBC Repositories #30769

Closed efenderbosch-atg closed 1 year ago

efenderbosch-atg commented 1 year ago

Affects: r2dbc 6, data-commons 3.1

Currently r2dbc "is new state detection" supports:

Another possibility is null @CreatedDate properties. I personally don't like nullable id properties and a version property doesn't make sense for my current project since there's only 1 user mutating an entity at a time, but the service does mutate entities, which was causing OptimisticLockingFailureException to be thrown when an old version comes through the API.

My solution was to implement Persistable, but it might be nice to support null @CreatedDate properties natively as an alternative"is new state detection".

My entities look like this:

@Immutable
interface AuditedPersistable<T> : Persistable<T> {
    @get:CreatedDate
    val createdAt: Instant?

    @get:LastModifiedDate
    val updatedAt: Instant?

    @JsonIgnore
    override fun isNew() = createdAt == null
}

@Table
data class Foo(
    private val id: UUIDv7,
    val bar: String,
    override val createdAt: Instant?,
    override val updatedAt: Instant?,
) : AuditedPersistable<UUIDv7> {
    @Id
    override fun getId() = id
}

I did try the custom EntityInformation route, but that proved to be too difficult when compared to the above solution.

Or maybe just add documentation with something like this as an example.

jhoeller commented 1 year ago

This looks like a Spring Data specific issue which we cannot deal with at the Spring Framework level. Please create a report for it in the Spring Data project: https://github.com/spring-projects/spring-data-relational