从多对一关系中嵌入属性

Embedding attributes from a many-to-one relationship

鉴于 Oracle Database HR sample schema 中的 COUNTRIESREGIONS 表:

COUNTRIES(country_id, country_name, region_id)
REGIONS(region_id, region_name)

而这个 Country 实体 class:

import javax.persistence.*;

@Entity
@Table(name = "COUNTRIES")
public class Country {
    @Id
    @Column(name = "COUNTRY_ID")
    private String id;

    @Column(name = "COUNTRY_NAME")
    private String name;
}

我想在单个 Country 实体 class 中映射两个表,也就是说,不创建单独的 Region 实体 class.

而不是这种多对一的关系:

@ManyToOne
@JoinColumn(name = "REGION_ID")
private Region region;

我想将一个简单的 String regionName 属性映射到 REGIONS.REGION_NAME,使用 REGIONS.REGION_ID = COUNTRIES.REGION_ID 作为连接条件。

JPA 2.0 支持这种映射吗?我应该使用哪些注释?

我相当确定您不能将 @SecondaryTable 与非 PK 连接一起使用,这正是您在这里所拥有的,即表不共享相同的 PK。

当时我能看到的最简单(可能也是唯一)的选择是在数据库上创建一个视图并将实体映射到该视图:

create view vw_countries as
select 
    c.country_id as id, c.country_name as name, r.region_name as region
from 
    countries c
inner join 
    regions r on r.region_id = c.region_id

实体:

@Entity
@Table(name = "vw_countries")
public class Country{

    @Id
    private Long id;

    private String name;

    private String region;
}