Danilo Piazzalunga
Danilo Piazzalunga

Reputation: 7802

Embedding attributes from a many-to-one relationship

Given the COUNTRIES and REGIONS tables from Oracle Database HR sample schema:

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

And this Country entity 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;
}

I would like to map both tables within a single Country entity class, that is, without creating a separate Region entity class.

Instead of this many-to-one relationship:

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

I would like to have a simple String regionName attribute mapped to REGIONS.REGION_NAME, using REGIONS.REGION_ID = COUNTRIES.REGION_ID as the join condition.

Is this kind of mapping supported in JPA 2.0? Which annotations should I use?

Upvotes: 0

Views: 41

Answers (1)

Alan Hay
Alan Hay

Reputation: 23226

I'm fairly sure you can't use @SecondaryTable with a non-PK join which is what you'd have here i.e. the tables do not share the same PK.

The simplest (and probably only) option I can see then is to create a view on the DB and map an Entity to that:

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:

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

    @Id
    private Long id;

    private String name;

    private String region;
}

Upvotes: 1

Related Questions