简体   繁体   中英

JPA entity is not persisted with my extra field

class Extra {
    int a;
}

@Entity
@Table(name = "data_table")
@Data
class Data {
    @Column int state;
    @Column(name = "extra") String _extra;

    @Transient Extra extra;

    @PostLoad
    void preLoad() {
        extra = mapper.readValue(_extra, Extra.class);
    }

    @PrePersist
    @PreUpdate
    void prePersist() {
        _extra = mapper.writeValueAsString(extra);
    }
}

Data data = jpaRepository.findOne(...);
data.setState(1);
data.getExtra().setA(1);
jpaRepository.save(data);

I want to use extra string column as Extra object. So I made @PostLoad, @PrePersist callbacks, which are converting extra column. But, when I persist data object, state value is persisted, but extra column (Data._extra) is not persisted. What did I do wrong?

Your defined extra object is @Transient . Transient objects aren't saved to DB.

If you really meant to ask about extra.a then the answer of @Abdullah G if right.

But if you made a typo then you probably meant _extra field.

Hibernate caches the value just being persisted so you're getting a cached old object in @PreUpdate callback.

UPDATE The solution I've found is to use

@Column(name = "password", insertable = false, updatable = false)

instead of @Transient annotation. However, it creates a column in the database that is always null.


Your save method - is it using merge? Since Extra is transient, it is invisible to JPA and would not be merged into the managed instance. So it will be null when the preUpdate method is called. you'll have to write your own save method to merge in transient values if you need them.

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