简体   繁体   English

Java 非持久但可序列化的变量

[英]Java non-persistent but serializable variable

In java, how can I declare a variable which is not persistent to a database but it is serializable so that the variable is present in JSON representation of the object containing the variable?在 java 中,我如何声明一个对数据库不持久但可序列化的变量,以便该变量出现在包含该变量的 object 的 JSON 表示中?

I used the annotation @javax.persistence.Transient , but it doesn't work the way I want since @Transient variables are not serializable.我使用了注释@javax.persistence.Transient ,但它没有按照我想要的方式工作,因为@Transient变量不可序列化。

The issue may be solved by a specific workaround using modifiers.该问题可以通过使用修饰符的特定解决方法来解决。 In order to avoid persisting fields, you have 4 options: marking the field with the modifier static , final or transient ;为了避免持久字段,您有 4 个选项:使用修饰符staticfinaltransient标记字段; or adding the @Transient annotation.或者添加@Transient注解。 Each of these will prevent the field from being persisted into the DB (see here ).这些中的每一个都会阻止该字段被持久化到数据库中(参见此处)。

Not all these limitations also apply to serialization though.不过,并非所有这些限制都适用于序列化。 Static and transient modifiers will prevent serialization, but final modifier will not - it will not be persisted but will be serialized (Deserializing in this case is a bit longer, but possible). Statictransient修饰符将阻止序列化,但final修饰符不会 - 它不会被持久化但会被序列化(在这种情况下反序列化会稍微长一些,但可能)。

I hope this will be applicable to your issue.我希望这将适用于您的问题。

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

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