如何访问@EmbeddedId的字段? [英] How to access fields of @EmbeddedId?
问题描述
我有一个具有复合主键的@Entity
.因此,我创建了一个包含PK字段的@EmbeddedId
.
I have an @Entity
that has a composite primary key. Therefore I created an @EmbeddedId
holding the PK fields.
问题:直接通过id.*
访问这些字段是否更好,还是应该在父类中创建getter/setter?
Question: is it better to access those fields by id.*
directly, or should I create getter/setter in the parent class?
示例:
@Entity
public class MyPerson {
@EmbeddedId
private PersonId id;
public String getFirstname() {
return id.getFirstname();
}
public String getLastname() {
return id.getLastname();
}
public LocalDate getDob() {
return id.getDob();
}
}
@Embeddable
public class PersonId implements Serializable {
private String firstname;
private String lastname;
private LocalDate dob;
//getter+setter as well
}
我最好使用person.getFistname()
还是person.getId().getFirstname()
?
前者更为清晰,但缺点是我必须在MyPerson
和PersonId
中都创建吸气剂.
The former is more clear, but with the drawback that I'd have to create the getters both in MyPerson
and in PersonId
.
首选的访问方式是什么,为什么?
What should be the preferred way to access, and why?
推荐答案
您不必创建属性
private PersonId id
替代项是
@Entity @IdClass(PersonId.class)
public class MyPerson {
@Id private String firstname;
@Id private String lastname;
@Id private LocalDate dob;
// Getters and setters here
}
并仅将PersonId用于加载 MyPerson 实体:
And use PersonId only for loading MyPerson entities:
PersonId peronId = new PersonId(firstname, lastname, dob);
MyPerson person = session.get(MyPerson.class, personId);
这篇关于如何访问@EmbeddedId的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!