JPA从多个表获取到具有命名查询的单个POJO

时间:2014-12-18 08:13:56

标签: java mysql jpa named-query

我一直在尝试将两个不同的表中的数据提取到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;
}

WareHouseWorkingHours具有一对多关系,fcId是连接它们的列。

在我的用例中,我必须在上面定义的单个实体WareHouse中获取WorkingHours个详细信息及其WareHouse。我如何实现这一目标?

命名查询(下方)仅提取WareHouse数据,WorkingHours显示为空。数据模型错了吗?或者查询错了? (我认为JPA会在给出注释OneToManyFetchType等时自动从相关表中获取。)

<named-query name="searchByFcId">
        <query>
            <![CDATA[
            select f from WareHouse f where f.fcId = :fc_id
            ]]>
        </query>
    </named-query>

1 个答案:

答案 0 :(得分:2)

您可以尝试以下映射。 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;
}

WorkingHours:

@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;
}