問題描述
主題說明了一切......到目前為止,我認(rèn)為人們?cè)?getter 和/或 setter 上聲明注釋沒有任何優(yōu)勢(shì).對(duì)我來(lái)說,這只是將注釋分散到類中的缺點(diǎn),這會(huì)使類更不可讀.
Subject says it all... I see no advantage of people declaring annotations on the getters and/or setters so far. For me this only has the disadvantage of spreading the annotations over the class, which can make the class more unreadable.
在字段上添加注釋明顯減少了需要幫助時(shí)發(fā)布的代碼量.不過,這只是一個(gè)很小的優(yōu)勢(shì).但是在方法上添加注釋對(duì)我來(lái)說毫無(wú)用處.
Putting the annotations on the fields clearly reduces the amount of code to post when needing help. This is just a tiny advantage though. But putting annotations on methods would serve no purpose to me.
推薦答案
在方法上添加注釋會(huì)強(qiáng)制 JPA 通過方法訪問屬性.當(dāng)對(duì)象的內(nèi)部狀態(tài)與數(shù)據(jù)庫(kù)模式不同時(shí),這是有意義的:
Putting annotations on methods forces JPA to access properties via methods. It makes sense when internal state of your object differs from the database schema:
@Entity
public class Employee {
private String firstName;
private String lastName;
@Column(name = "EMP_NAME") // Due to legacy database schema
public String getName() {
return fisrtName + " " + lastName;
}
public void setName(String name) {
...
}
... Getters and setters for firstName and lastName with @Transient ...
}
在 JPA 2.0 中,您可以使用 @Access
在細(xì)粒度級(jí)別指定訪問類型:
In JPA 2.0 you can specify access type at fine-grained level with @Access
:
@Entity @Access(AccessType.FIELD)
public class Employee {
@Access(AccessType.PROPERTY) @Column(name = "EMP_NAME")
public String getName() { ... }
... other properties have field access ...
}
這篇關(guān)于在使用 JPA 映射類時(shí),為什么有人要在 getter 或 setter 上添加注釋?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!