简体   繁体   English

如何使用Spring Data实现只读属性?

[英]How to implement a read-only property with Spring Data?

This should be a simple thing to do! 这应该是一件简单的事情! But I've been unable to find an answer so far. 但到目前为止我一直无法找到答案。 Either I'm missing something obvious, or else I'm missing something obvious... 要么我错过了一些明显的东西,否则我会遗漏一些明显的东西......

I have a class, say Person. 人说,我有一节课。 With three fields - "id", "name" and "reputation". 有三个字段 - “id”,“name”和“reputation”。 Let's say that I am willing to take updates to "name" but not to "reputation". 让我们说我愿意更新“名称”而不是“声誉”。 I'd like Spring Data to fetch the value of "reputation" when retrieving from DB, but ignore it when I'm saving the bean. 我希望Spring Data在从DB中检索时获取“信誉”的值,但在保存bean时忽略它。

@Transient annotation is there, but then Spring completely ignores the field and doesn't populate it at all. @Transient注释就在那里,但是Spring完全忽略了该字段并且根本没有填充它。 Ideally, I'm looking for something like @ReadOnly annotation. 理想情况下,我正在寻找类似@ReadOnly注释的东西。

More details 更多细节

  • I'm using Spring Data for Neo4j, but I believe this would apply to any Spring Data flavor. 我正在使用Spring Data for Neo4j,但我相信这适用于任何Spring Data风格。
  • This is a backend for Jersey/Jackson-based RESTful service. 这是基于Jersey / Jackson的RESTful服务的后端。 ** When I satisfy the GET request, I'd like to serve the "reputation" value. **当我满足GET请求时,我想提供“声誉”值。 But when I receive a PUT update I don't want to take it. 但是当我收到PUT更新时,我不想接受它。 ** So far I could use Jackson features. **到目前为止我可以使用杰克逊的功能。 But I'd like to be able to update the DB without having to fetch the existing Person object first. 但我希望能够更新数据库而无需首先获取现有的Person对象。
  • The only way I can figure for making this work is to define two classes - one with "reputation" field and one without. 我可以想象的唯一方法是定义两个类 - 一个具有“信誉”字段而另一个没有。 But this seems really clunky. 但这看起来很笨重。 Isn't there something simpler? 是不是有更简单的东西?

You can use a transient property without a setter. 您可以在没有setter的情况下使用transient属性。 That transient property would return the db property value that is to be protected. 该transient属性将返回要保护的db属性值。

you can use @ReadOnlyProperty from org.springframework.data.annotation. 你可以使用org.springframework.data.annotation中的@ReadOnlyProperty。 see ReadOnlyProperty 请参阅ReadOnlyProperty

@ReadOnlyProperty
private Object readOnlyValue;

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

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