英文:
JPA - An entity's property type depends on a column value
问题
我正在使用第三方数据库,其中有以下表格:
Node
----
id(非空整数)
fKey(可空的最大长度字符串)
refTable(可空的最大长度字符串)
fkey
是 refTable
主键的值。refTable
包含以下值之一:Car
、Truck
或 Boat
。我的节点实体目前如下:
@Entity
@Data
public class Node {
@Id
private Long id;
@Column(name = "fKey")
private String foreignKey;
@Column(name = "refTable")
private String targetTable;
}
但是我希望当 targetTable
为 Car
时,节点实体引用一个 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论