JPA 两个 many-to-one 关联同一实体类型的实现
结论先说:在 JPA 中,@ManyToOne 字段还是应该声明成实体类型(Persona),数据库列里存的是外键 id。如果希望 REST JSON 只返回 id,就在 DTO 或序列化层处理;把关联字段改成 Long,同时又指望还能做双向对象导航,是行不通的。双向映射的做法是:Relationship 用两个 @ManyToOne 指向不同的外键列,Persona 用两个 @OneToMany(mappedBy = ...),分别接住“作为 first”和“作为 second”的边。
1. 实体映射
Relationship:
@Entity
@Table(name = "relationships")
public class Relationship {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long uuid;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "first_persona_uuid", nullable = false)
private Persona firstPersona;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "second_persona_uuid", nullable = false)
private Persona secondPersona;
// getters/setters
}
Persona:
@Entity
@Table(name = "personas")
public class Persona {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long uuid;
@OneToMany(mappedBy = "firstPersona")
private List<Relationship> relationshipsAsFirst = new ArrayList<>();
@OneToMany(mappedBy = "secondPersona")
private List<Relationship> relationshipsAsSecond = new ArrayList<>();
public void addRelationshipAsFirst(Relationship r) {
relationshipsAsFirst.add(r);
r.setFirstPersona(this);
}
public void removeRelationshipAsFirst(Relationship r) {
relationshipsAsFirst.remove(r);
r.setFirstPersona(null);
}
public void addRelationshipAsSecond(Relationship r) {
relationshipsAsSecond.add(r);
r.setSecondPersona(this);
}
public void removeRelationshipAsSecond(Relationship r) {
relationshipsAsSecond.remove(r);
r.setSecondPersona(null);
}
}
这两个集合不能合并成一个 @OneToMany,因为对应的是不同的外键列。如果 API 需要返回合并后的 relationships 数组,在 DTO 层把 relationshipsAsFirst 和 relationshipsAsSecond 的 id 合并即可。
2. 请求只传 id:用 DTO,不传整个 Persona
请求 DTO 可以只接收 id:
public record RelationshipRequest(
Long firstPersonaId,
Long secondPersonaId
) {}
服务层再把 id 解析成实体引用:
@Transactional
public Relationship create(RelationshipRequest req) {
Persona first = personaRepository.findById(req.firstPersonaId())
.orElseThrow(() -> new IllegalArgumentException("firstPersona not found"));
Persona second = personaRepository.findById(req.secondPersonaId())
.orElseThrow(() -> new IllegalArgumentException("secondPersona not found"));
Relationship r = new Relationship();
r.setFirstPersona(first);
r.setSecondPersona(second);
first.addRelationshipAsFirst(r);
second.addRelationshipAsSecond(r);
return relationshipRepository.save(r);
}
请求 JSON 里就传普通数字:
{
"firstPersonaId": 5,
"secondPersonaId": 6
}
如果只需要外键,而且能保证 id 有效,可以用 personaRepository.getReferenceById(id) 获取代理,少查一次;如果 id 可能不存在,就用 findById 并显式校验。
3. 响应只返回 id:DTO 映射
不要让 Jackson 直接序列化实体图,否则容易出现懒加载异常、循环引用,或者把整个 Persona 带出来。响应 DTO 可以这样写:
public record RelationshipResponse(
Long uuid,
Long firstPersonaId,
Long secondPersonaId
) {}
映射时取外键 id:
public RelationshipResponse toResponse(Relationship r) {
return new RelationshipResponse(
r.getUuid(),
r.getFirstPersona().getUuid(),
r.getSecondPersona().getUuid()
);
}
需要输出 first_persona、second_persona 这类字段名时,在 DTO 上加 @JsonProperty("first_persona") 等注解即可。
4. 如果确实要在实体上直接读外键 id
可以保留 @ManyToOne 作为可写关联,再加一个只读 id 字段。两者映射同一列,写入仍由关联字段负责:
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "first_persona_uuid", nullable = false)
@JsonIgnore
private Persona firstPersona;
@Column(name = "first_persona_uuid", insertable = false, updatable = false)
private Long firstPersonaId;
这适合读取时顺手拿 id 的场景,但不要拿它代替请求 DTO。请求体仍然只暴露 firstPersonaId 和 secondPersonaId 比较好。
5. 注意事项
@OneToMany一侧必须用mappedBy指向Relationship中真正的关联字段,否则会重复建外键列。- JPA 不会自动同步双向关系,新增或删除边时要调用 helper 方法维护两端。
- 不要在
Relationship -> Persona的@ManyToOne上随便加cascade = REMOVE,否则删除边可能误删 Persona;级联策略要按业务边界设计。 - 如果图是无向边,建议在数据库层加
(first_persona_uuid, second_persona_uuid)的唯一约束,或者在写入前统一排序两个 id,避免重复边。 - 返回 Persona 及其关系 id 时,用 DTO 查询或映射,并在事务内完成懒加载访问,或者使用
@EntityGraph/join fetch明确抓取策略。
备注:内容仅供参考。
