gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:14:54 28 4
gpt4 key购买 nike

在 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/

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