Reputation: 1908
I have one class that can reference one of multiple of classes.
The old classes are as structured as follows:
public class CarOne {
private int id;
private int type; //one
...
}
public class CarTwo {
private int id;
private int type; //two
...
}
public class CarThree {
private int id;
private int type; //three
...
}
They are NOT SupperMapped and they all exist in their own table with their own ID. There's nothing I can change about this, as it's been in production like this for quite a while now.
Now I need to add a new class:
public class Numberplate {
//here I'd like a one to one mapping to one of the classes?
}
One option I can think of myself is that I could add the OneToOne relation on the car objects, but I was hoping there was an option to use the 'id' and the 'type' as a discriminator to put the relation on the Numberplate side. Is there such a possibility?
(disclaimer: the examples are purely fictional, but the situation is not.)
Upvotes: 1
Views: 179
Reputation: 743
Why dont you use a TABLE_PER_CLASS Strategy ? with this strategy only concrete class have a corresponding table in database and the super class is only for sharing and grouping purpose.
Exemple you define an abstract class for all your CarClass (CarOne, CarTwo...) with a compounded primary key which is id and type.
@Embeddable
public class CarKey implements Serializable{
public Long id;
public String type;
}
Here you abstract class parent of all your car class
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class SuperCar{
@EmbeddedId
public CarKey id;
// Getter & Setter
}
Here code for each subclass
@Entity
public class CarOne extends SuperCar{
// specific attribute
}
Here code for your Nameplate class
@Entity
public class Numberplate {
@OneToOne
@JoinColumns({
@JoinColumn(name="car_id",referencedColumnName = "id"),
@JoinColumn(name="car_type",referencedColumnName = "type")
})
public SuperCar car;
}
Just take care of performance issue with this strategy especially if you have many subclasses.
Upvotes: 1
Reputation: 722
You can use the joined inheritance type, creating a superclass Car and then CarOne,CarTwo,CarThree must extend it. You can find a complete example of joined here
Upvotes: 1