Iker Aguayo
Iker Aguayo

Reputation: 4115

Update field in an entity with updatable=false returns the entity with the field with the new value

I am using spring-data-jpa and I have an entity with the following code:

@Id
@GeneratedValue
@Column(columnDefinition = "uuid")
private UUID id;

@Basic(optional = false)
@Column(updatable = false)
private long creationTimestamp;
... 

I use a org.springframework.data.jpa.repository.JpaRepository to do the pertinent CRUD operations.

When I firstly save the entity (e.g. creationTimestamp=1), the method save(entity) returns the saved entity (like the javadoc says) with the new id for further operations (like the javadoc says) and with the field creationTimestamp=1.

But later on, if I try to update this entity with a new creationTimestamp (e.g. creationTimestamp=2), again with the method save(entity), this method returns the entity with the field creationTimestamp=2 (which is not correct).

If I search with the method findById(given_id), the returned entity has the field creationTimestamp=1, which is correct because the column was defined as updatable=false.

The question is, why when I update, the method save(entity) returns the new value in creationTimestamp instead of the one that is in the database? Because I expect "the saved entity" (like the javadoc says).

Upvotes: 0

Views: 1218

Answers (2)

Samuel
Samuel

Reputation: 1159

How @Stefan said @Column(updatable = false) affects only database layer

Here in Stackoverflow, there are a question about this

If I understood that you are trying to do, I recommend that Spring manage this column with

        @Id
        @GeneratedValue
        @Column(columnDefinition = "uuid")
        private UUID id;

        @Basic(optional = false)
        @CreationTimestamp
        private java.sql.Timestamp creationTimestamp;

Using this implementation it isn't necessary you to code to set value in this attribute. You only create getter method.

Upvotes: 0

Stefan
Stefan

Reputation: 1803

This option does not make the attribute write protected. It means that the UPDATE statement sent to the database shall exclude this field.

Upvotes: 1

Related Questions