gpt4 book ai didi

java - 为什么 JPA Transient 注解在 Target 中有方法?

转载 作者:行者123 更新时间:2023-12-04 17:58:12 25 4
gpt4 key购买 nike

谁能用一个例子来解释为什么 JPA 中的 @Transient 注释也有 @Target 方法

我指的是文档 http://docs.oracle.com/javaee/5/api/javax/persistence/Transient.html

@Target(value={METHOD,FIELD})

提前致谢!

最佳答案

在 JPA 实体中,您可以注释字段或方法(getter)。 @Id 注释规定了这一点,这意味着如果您将 @Id 放在一个字段上,那么您所有的注释都应该放在字段上,但是如果您将它放在例如 @Id Long getId() 那么其他注释应该跟在后面。这就是为什么 @Transient 也可以在方法上的原因。

例如,如果你有这个

@Id
private Long id;

@Transient
private String someTransientField;

private Long getId() {
return this.id;
}

private String getSomeTransientField() {
return this.someTransientField;
}

然后 someTransientField 将被视为 transient 。但是如果 @Id 会留在场上,并且您将 @Transient 移动到 private String getSomeTransientField() 然后 someTransientField 将被视为持久性的,因为 @Id 在字段上,因此所有其他注释也应该在字段上。

所以 @Transient 对方法起作用的情况是这样的

private Long id;

private String someTransientField;

@Id
private Long getId() {
return this.id;
}

@Transient
private String getSomeTransientField() {
return this.someTransientField;
}

关于java - 为什么 JPA Transient 注解在 Target 中有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com