简体   繁体   English

SpringDataJPA持续存在:仅在查询时填充字段,但不保存

[英]SpringDataJPA persist: only populate a field when querying, but not save

I am using SpringDataJpa. 我正在使用SpringDataJpa。 Let's say I have an entity called USER (with properties first, last and level). 假设我有一个名为USER的实体(具有属性first,last和level)。 Which annotation should I use on the level property, so it's only populated when querying, but not ignored during saving the object to database? 我应该在level属性上使用哪个批注,以便仅在查询时填充该批注,而在将对象保存到数据库期间不会被忽略? I have tried @Transient , but then the field is ignored when querying... 我试过@Transient ,但是查询时忽略该字段...

I would try the following. 我会尝试以下。

First make sure that you use JPA Field Access - so your JPA provider is not relying on getters and setters. 首先 ,请确保使用“ JPA现场访问” -这样您的JPA提供程序就不会依赖getter和setter。 If your @Id annotation is set on the field and not the getter you should be fine. 如果在字段上设置了@Id注释,而不是在getter上设置,则应该没问题。 See the accepted answer of this question for more details on the JPA access type: 有关JPA访问类型的更多详细信息,请参见此问题的可接受答案:

What is the purpose of AccessType.FIELD, AccessType.PROPERTY and @Access AccessType.FIELD,AccessType.PROPERTY和@Access的用途是什么

Additionally you do not provide a setter for your level property . 此外,您不为您的level属性提供设置器 So the field can just be read by the caller. 因此,该字段只能由调用方读取。

Further more you can express that the field cannot be written using the @Column annotation on the level property. 此外,您还可以表示无法使用level属性上的@Column注释写入字段

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

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

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