我一直在尝试将数据从 2 个不同的表获取到 JPA 中的单个实体,但没有结果。
保存两个不同表中数据的实体如下:
@Data @Entity @JsonSnakeCase
public class WareHouse {
@Id
@GeneratedValue
private long id;
@Column(unique = true)
private String fcId;
@Enumerated(EnumType.STRING)
private FCStatus status;
@OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER, mappedBy = "fcId")
private List<WorkingHours> workingHours;
@Enumerated(EnumType.STRING)
private IntegrationType integrationType;
}
另一个实体WorkingHours
是:
@Data
@Entity
@JsonSnakeCase
public class WorkingHours {
@Id
@GeneratedValue
private long id;
private String fcId;
private LocalDate date;
private DateTime start;
private DateTime end;
}
表 WareHouse
和 WorkingHours
具有一对多关系,fcId
是连接它们的列。
在我的用例中,我必须在单个实体 WareHouse
中获取 WareHouse
详细信息及其 WorkingHours
,如上面所定义。我该如何实现这一目标?
命名查询(如下)仅获取 WareHouse
数据,而 WorkingHours
为空。数据模型是不是错了?或者查询有误? (我认为当给定注释 OneToMany
和 FetchType
等时,JPA 会自动从相关表中获取数据。)
<named-query name="searchByFcId">
<query>
<![CDATA[
select f from WareHouse f where f.fcId = :fc_id
]]>
</query>
</named-query>
最佳答案
您可以尝试以下映射。 JPA 2.0 规范说明 (11.1.21) 说明:
If the referencedColumnName element is missing, the foreign key is assumed to
refer to the primary key of the referenced table.
但是它还指出:
Support for referenced columns that are not primary key columns of the
referenced table is optional. Applications that use such mappings
will not be portable.
因此这是否有效将取决于您的提供商。
仓库:
@Data
@Entity
@JsonSnakeCase
public class WareHouse {
@Id
@GeneratedValue
private long id;
@Column(unique = true)
private String fcId;
@Enumerated(EnumType.STRING)
private FCStatus status;
@OneToMany(mappedBy = "warehouse", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private List<WorkingHours> workingHours;
@Enumerated(EnumType.STRING)
private IntegrationType integrationType;
}
工作时间:
@Data
@Entity
@JsonSnakeCase
public class WorkingHours {
@Id
@GeneratedValue
private long id;
@ManyToOne
@JoinColumn(name = "fcId", referencedColumnName="fcid")
private Warehouse warehouse;
private LocalDate date;
private DateTime start;
private DateTime end;
}
关于java - JPA 使用命名查询从多个表获取单个 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541894/