简体   繁体   中英

JPA - Secondary Table mapping direction

I've got two tables:

CREATE TABLE Checkin (
  ID int primary key,
  foo varchar(100),
  bar varchar(100),
  FK_type int foreign key references Type(ID)
)

CREATE TABLE Type (
  ID int primary key,
  type varchar(100)
)

Since the secondary table only stores labels, I'd like to map the values directly into my entity. I figured it should be possible using @SecondaryTable...

@Table(name = "Checkin")
@SecondaryTable(name = "Type",
    pkJoinColumns = @PrimaryKeyJoinColumn(name="FK_type", referencedColumnName = "ID")
)
class Checkin {
  @Id
  private Integer id;

  private String foo;
  private String bar;

  @Column(name="FK_type", table="Type")
  private String type;
}

Unforunately, it would seem that the @SecondaryTable annotation works the other way around, meaning it wants my actual primary data table with the most columns to be the one joining. So I get thrown the error

Invalid column name 'FK_type'.

Is there a way to solve that through different annotations or do I really need to build the whole construct the other way round and have the main entity refer to "Type" and "Chekin" be the secondary table?

You should join Type entity in Checkin:

class Checkin {
      @Id
      private Integer id;
    
      private String foo;
      private String bar;
    
      @OneToOne(cascade = CascadeType.ALL)
      @JoinColumn(name = "type_id", referencedColumnName = "id")
      private Type type;
    }

Try to correct this:

@Column(name="FK_type", table="Type")
private String type;

to this:

@Column(name="type", table="Type")
private String type;

The table Type just do not have the FK_type column, as I understand you want to use Type.type here.

PS You can omit to use referencedColumnName if this is a reference to the PK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM