Reputation: 455
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?
Upvotes: 0
Views: 91
Reputation: 476
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
Upvotes: 1