将三个表建模为三个实体:
@Entity
@Table(name="event")
public class Event {
public Long datetime;
public String name;
public Long processId;
}
@Entity
@Table(name="process")
public class Process {
public Long Id;
public Long sequence;
public Name name;
}
@Entity
@Table(name="operation")
public class Operation {
public Long Id;
public Long datetime;
public Long sequence;
}
任何唯一的 process-operation-sequence 单条记录都由具有 3-way join 约束的 SQL 获得:
SELECT *
FROM event e, process p, operation q
WHERE e.processId = p.id
AND e.datetime = q.datetime
AND p.sequence = q.sequence
为了在 JPA 中实现它,我必须列出一个操作列表,通过 JQPL 相等 p.sequence = q.sequence 将其明确缩小到单个记录
@Entity
@Table(name="event")
public class Event {
public Long datetime;
public String name;
public Long processId;
@OneToOne
@JoinColumn(
name = "processId", referencedColumnName="id",
insertable=false, updatable=false)
private Process process;
@OneToMany
@JoinColumn(
name = "datetime", referencedColumnName="datetime",
insertable=false, updatable=false)
private List<Operation> operations;
}
其中 JPQL 指定了传递的第三个连接约束:
SELECT e FROM Event e
INNER JOIN FETCH e.process p
INNER JOIN FETCH e.operations q
WHERE p.sequence = q.sequence
但是,我希望在实体 POJO 中对所有三个约束进行建模。不应该有办法单独使用 JPA 注释进行三向连接吗?如以下实体伪代码所示:
@Entity
@Table(name="event")
public class Event {
public Long datetime;
public String name;
public Long processId;
@OneToOne
@JoinColumn(
name = "processId", referencedColumnName="id",
insertable=false, updatable=false)
private Process process;
@OneToOne
@JoinColumn(
name = "datetime", referencedColumnName="datetime",
insertable=false, updatable=false)
@JoinColumn(
name = "process.sequence", referencedColumnName="sequence",
insertable=false, updatable=false)
private Operation operations;
}
这样就没有必要在 JPQL 中指定传递连接约束
SELECT e FROM Event e
INNER JOIN FETCH e.process p
INNER JOIN FETCH e.operations q
如何使用 JPA 注释对传递连接进行建模?