java - JPA 使用命名查询从多个表获取单个 POJO

标签 java mysql jpa named-query

我一直在尝试将数据从 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;
}

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

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

命名查询(如下)仅获取 WareHouse 数据,而 WorkingHours 为空。数据模型是不是错了?或者查询有误? (我认为当给定注释 OneToManyFetchType 等时,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/

相关文章:

java - 重复的键值JPA

java - 如何在满足条件时停止正在运行的线程?

java - 使用 Java 读取 Azure Blob 存储中文件的文件属性

java - 从 Android 应用程序到动态 Web Servlet 的通信

java - 为什么我收到 HHH015011 : Unable to locate static metamodel field?

java - JPA/hibernate : Map many-to-many relationship when join table has own primary key

java - Hibernate通过无状态 session 保存延迟获取的实体

java - JVM 什么时候决定重用旧的 lambda?

mysql - 'on clause' 中的未知列

mysql - 如何为mysql变量添加参数?