简体   繁体   English

使字段临时进行序列化,但对JPA非临时

[英]Make a field transient for serialization, but non-transient for JPA

Question: 题:
Is it possible to have a field persisted by JPA but skipped by serialization? JPA是否可以保留一个字段,但序列化会跳过该字段?

It is possible to achive the opposite (JPA skips a field and serialization doesn't), and if this feature is used, surely the reverse would be useful. 可能出现相反的情况(JPA跳过字段,而序列化则不这样做),如果使用了此功能,则肯定可以相反。

Something like this: 像这样:

@Entity 
class MyClass {
    // Other fields.

    @NonTransient
    private transient String strangeField;
}

I am asking mostly out of curiosity, so I don't have a specific context. 我主要是出于好奇而问,所以我没有特定的背景。

One option is to use property access on the entity. 一种选择是在实体上使用属性访问。 Then, mark the field as transient. 然后,将该字段标记为瞬态。 JPA will ignore the field and only use the getter. JPA将忽略该字段,仅使用getter。 Thus, serialization skips the field, and JPA uses the getter. 因此,序列化会跳过该字段,而JPA使用getter。

@Entity(AccessType.Property)
class MyClass {
    // Other fields.

    private transient String strangeField;

    public String getStrangeField() {
        return strangeField;
    }

    public void setStrangeField(String strangeField) {
        this.strangeField = strangeField;
    }
}

您需要使用属性访问或使用XML来映射实体而不是注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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