JPA – 实体的属性类型取决于列的值

huangapple go评论74阅读模式
英文:

JPA - An entity's property type depends on a column value

问题

我正在使用第三方数据库,其中有以下表格:

Node
----
id(非空整数)
fKey(可空的最大长度字符串)
refTable(可空的最大长度字符串)

fkeyrefTable 主键的值。refTable 包含以下值之一:CarTruckBoat。我的节点实体目前如下:

@Entity
@Data
public class Node {
  
  @Id
  private Long id;

  @Column(name = "fKey")
  private String foreignKey;

  @Column(name = "refTable")
  private String targetTable;
}

但是我希望当 targetTableCar 时,节点实体引用一个 Car 实体。类似于这样:

@Entity
@Data
public class Node {
  
  @Id
  private Long id;

  @ManyToOne
  @JoinColumn(name = "carId")
  private Car car;
  
  // 对于 truck 和 boat,这里也可以有,并且在 refTable 引用 Car 时为 null

}

我该如何设置这个映射?

英文:

I'm working with a 3rd party database with the following table:

Node
----
id (int not null)
fKey (varchar(max) null)
refTable (varchar(max) null)

fkey is the value of the primary key of refTable. refTable contains one the following values Car, Truck, or Boat. My node entity currently looks like:

@Entity
@Data
public class Node {
  
  @Id
  private Long id;

  @Column(name = "fKey")
  private String foreignKey;

  @Column(name = "refTable")
  private String targetTable;
}

But I'd prefer the node entity refer to a Car entity when targetTable is Car. Something like this:

@Entity
@Data
public class Node {
  
  @Id
  private Long id;

  @ManyToOne
  @JoinColumn(name = "carId")
  private Car car;
  
  // ok with having truck and boat 
  // here too and being null when refTable refers to Car

}

How can I set up this mapping?

答案1

得分: 1

更好的方法是使用继承。你应该将你的Node类变为MainClass,并从中继承到Car、Truck和Boat类。

@Entity
@Data
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "refTable")
public class Node {

  @Id
  private Long id;



}

你的子类实现应该类似于:

@Entity
@Data
@DiscriminatorValue("Car")
public class CarNode extends Node {

  @ManyToOne
  @JoinColumn(name = "fKey")
  private Car car;

}

对于Truck和Boat也是相同的。你查询Nodes时会返回CarNodes、TruckNodes或BoatNodes。

英文:

A better aproach would be to use inheritance. You should turn your Node class the MainClass and inherit from it to Car, Truck and Boat

@Entity
@Data
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = “refTable”)
public class Node {
  
  @Id
  private Long id;

  
  
}

Your subclassed implementation should look like

@Entity
@Data
@DiscriminatorValue(“Car”)
public class CarNode extends Node {
  
  @ManyToOne
  @JoinColumn(name = "fKey")
  private Car car;
  
}

The same for Truck and Boat. Your query for Nodes would return you CarNodes, TruckNodes or BoatNodes

huangapple
  • 本文由 发表于 2020年8月26日 02:08:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63584771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定