考虑下表:
CREATE TABLE Participations
(
roster_id INTEGER NOT NULL,
round_id INTEGER NOT NULL,
ordinal_nbr SMALLINT NOT NULL ,
was_withdrawn BOOLEAN NOT NULL,
PRIMARY KEY (roster_id, round_id, ordinal_nbr),
CONSTRAINT participations_rosters_fk FOREIGN KEY (roster_id) REFERENCES Rosters (id),
CONSTRAINT participations_groups_fk FOREIGN KEY (round_id, ordinal_nbr) REFERENCES Groups (round_id , ordinal_nbr)
)
这里是JPA 1.0 @IdClass实体类:
@Entity
@Table(name = "Participations")
@IdClass(value = ParticipationId.class)
public class Participation implements Serializable
{
@Id
@Column(name = "roster_id", insertable = false, updatable = false)
private Integer rosterId;
@Id
@Column(name = "round_id", insertable = false, updatable = false)
private Integer roundId;
@Id
@Column(name = "ordinal_nbr", insertable = false, updatable = false)
private Integer ordinalNbr;
@Column(name = "was_withdrawn")
private Boolean wasWithdrawn;
@ManyToOne
@JoinColumn(name = "roster_id", referencedColumnName = "id")
private Roster roster = null;
@ManyToOne
@JoinColumns(value = {@JoinColumn(name = "round_id", referencedColumnName = "round_id"), @JoinColumn(name = "ordinal_nbr", referencedColumnName = "ordinal_nbr")})
private Group group = null;
public Participation()
{
}
public Integer getRosterId()
{
return rosterId;
}
public void setRosterId(Integer rosterId)
{
this.rosterId = rosterId;
}
public Integer getRoundId()
{
return roundId;
}
public void setRoundId(Integer roundId)
{
this.roundId = roundId;
}
public Integer getOrdinalNbr()
{
return ordinalNbr;
}
public void setOrdinalNbr(Integer ordinalNbr)
{
this.ordinalNbr = ordinalNbr;
}
public Boolean getWasWithdrawn()
{
return wasWithdrawn;
}
public void setWasWithdrawn(Boolean wasWithdrawn)
{
this.wasWithdrawn = wasWithdrawn;
}
public Roster getRoster()
{
return roster;
}
// ???
public void setRoster(Roster roster)
{
this.roster = roster;
}
public Group getGroup()
{
return group;
}
// ???
public void setGroup(Group group)
{
this.group = group;
}
...
}
一般来说,如果关联设置器与冗余字段同步,那么这里是rosterId,roundId和ordinalNbr?:
// ???
public void setGroup(Group group)
{
this.group = group;
this.roundId = group.getRoundId();
this.ordinalNbr = group.getOrdinalNbr();
}
由于
答案 0 :(得分:3)
是的,它们应该保持同步。虽然因为它们是Id的一部分,所以你永远不应该改变它们,所以它实际上只是新对象的一个问题。
如果你不保持同步,那么对于一个新对象,它们将为null / 0,这可能不是很好。 JPA中没有任何魔法可以让你保持同步。
如果您从数据库中读取对象,那么它们将是粗略的同步,但您负责在内存中维护对象的状态,包括重复字段和双向映射。
如果您使用的是JPA 2.0,为什么还要复制Ids呢?您可以删除routersId和roundId,只需将@Id添加到@ManyToOnes。