如何使用 Hibernate/JPA 使用外键从另一个 table 检索一列

How to retrieve ONE column from another table with Foreign key using Hibernate / JPA

我想使用外键“MODEL_ID”从 TT_CARS table 中仅检索一列“MODEL_NAME”, 我尝试了以下代码,该代码有效,但它 returns 整个 CARS 对象。

@JoinColumn(name = "MODEL_ID", referencedColumnName = "ID")
@ManyToOne(fetch = FetchType.EAGER)
private CARS cars;

我也尝试了下面的代码,它也不起作用

@SecondaryTable(name = "TT_CARS", pkJoinColumns = @PrimaryKeyJoinColumn(name = "ID", referencedColumnName="MODEL_ID"))

是否有其他方法可以使用休眠和 JPA 仅检索列 (MODEL_NAME)?

备注:modelName 应该是 Options class.

的一部分

我的代码

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name = "TT_OPTIONS")
public class Options  {

    @Id
    @Column(name = "ID")
    private String id;

    @NotNull
    @Column(name = "DESCRIPTION", nullable = false)
    private String description;

    @Column(name = "MODEL_ID") // Foreign key
    private Long modelId;

    @Column(name = "MODEL_NAME", table = "TT_CARS") // this is the column name I would like to retrieve from the TT_CARS table
    private String modelName;

    // getters and setters
}

您可以使用 @Formula。它是 read-only 可以通过自定义子查询检索的计算列。它不存在于目标 table.

Defines a formula (derived value) which is a SQL fragment that acts as a @Column alternative in most cases. Represents read-only state.

示例:

@Entity
@Table(name = "TT_OPTIONS")
public class Options  {

    @Id
    @Column(name = "ID")
    private Long id;

    @Column(name = "DESCRIPTION", nullable = false)
    private String description;

    @Column(name = "MODEL_ID") 
    private Long modelId;

    @Formula("(select TT_CARS.MODEL_NAME from TT_CARS where TT_CARS.ID = MODEL_ID)")
    private String modelNameFormula;
}

@Entity
@Table(name = "TT_CARS")
public class Cars {
    @Id
    @Column(name = "ID")
    private Long id;

    @Column(name = "MODEL_NAME")
    private String modelName;
}

Hibernate 生成的本机查询:

    select
        options0_.id as id1_4_0_,
        options0_.description as descript2_4_0_,
        options0_.model_id as model_id3_4_0_,
        (select
            TT_CARS.MODEL_NAME 
        from
            TT_CARS 
        where
            TT_CARS.ID = options0_.MODEL_ID) as formula1_0_ 
    from
        tt_options options0_ 
    where
        options0_.id=?

@SecondaryTable 专为@OneToOne 关系设计,将多个 table 映射到同一实体。它不适用于@ManyToOne 关系。