java - JPA 2.0 字段注释与方法注释

标签 java database jpa

在 JPA 2.0 中,注释字段和注释方法(通常是 getter)之间有什么区别?

带有字段注释的示例

@Entity
public class MainEntity {

    @Id
    private Long id

    @OneToMany
    private RelatedEntity relatedEntity

    //getters and setters and possible other methods
    ...

}

带有方法注释的示例

@Entity
public class MainEntity {

    @Id
    private Long id;

    private RelatedEntity relatedEntity

    //getters and setters and possible other methods
    @OneToMany
    public RelatedEntity getRelatedEntity(){
           return relatedEntity
    }

    //other methods etc
    ...

 }

最佳答案

通过JPA,您可以使用这两种方法将表的列映射到实体类中;从模式生成的角度或翻译查询的角度来看,字段/方法访问不会改变任何内容。一般来说,字段注释更干净(像Spring这样的框架鼓励它),方法注释可以给你更多的灵 active (就像从抽象实体类继承一样)。

请注意,在您的第二个示例中存在错误:

@Entity
public class MainEntity {

    private Long id;

    private RelatedEntity relatedEntity

    //getters and setters and possible other methods
    @Id
    public Long getId() {
        return id;
    }

    @OneToMany
    public RelatedEntity getRelatedEntity(){
           return relatedEntity
    }

    //other methods etc
    ...
 }

关于java - JPA 2.0 字段注释与方法注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40462865/

相关文章:

hibernate - Spring 中与 Hibernate 的 SQL 连接异常

java - Spring 3 中的 maven 多模块配置,明智与否?

java - Eclipse - 如何打开 sql 文件?

java - 由 : org. hibernate.QueryException 引起:无法解析属性:

mysql - 当没有 "having"子句时, "where"和 "group by"是否完全等价?

mysql - 在 MySQL 中,将每一行中的值设置为同一行上的 DATEDIFF 计算

java - hibernate OGM : Having trouble starting MongoDB database

java - 删除包含 null 的字符串

java - Java Android Studio 新手,需要一些指导

java - bitmap.compress(Bitmap.compressFormat.JPEG,100, baos) 给我 java.lang.OutOfMemoryError