简体   繁体   中英

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 (eg 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 (eg 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).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM