在使用 JPA 映射类时,为什么有人要在 getter 或 setter 上添加注释?

Why should anybody put annotations on the getters or setters when using JPA to map the classes?(在使用 JPA 映射类时,为什么有人要在 getter 或 setter 上添加注释?)
本文介绍了在使用 JPA 映射类时,为什么有人要在 getter 或 setter 上添加注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

主题说明了一切......到目前为止,我认为人们在 getter 和/或 setter 上声明注释没有任何优势.对我来说,这只是将注释分散到类中的缺点,这会使类更不可读.

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.

在字段上添加注释明显减少了需要帮助时发布的代码量.不过,这只是一个很小的优势.但是在方法上添加注释对我来说毫无用处.

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.

推荐答案

在方法上添加注释会强制 JPA 通过方法访问属性.当对象的内部状态与数据库模式不同时,这是有意义的:

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 在细粒度级别指定访问类型:

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 ...
}

这篇关于在使用 JPA 映射类时,为什么有人要在 getter 或 setter 上添加注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)