I have a base abstract class defined like so :
@MappedSuperclass
public abstract class State implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name = "stateCode")
private String code;
}
The concrete classes such as StateA, StateB... StateZ were defined like so:
@Entity
@Table(name = "stateA")
public class StateA extends State implements serializable{
}
There's also a Region class like so:
@Entity
@Table(name = "region")
public class Region {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
@Column(name = " regionCode")
private String regionCode;
}
Each of the concrete State classes references the Region class in the database.
However, I'm struggling to have a OneToMany mapping like this in the Region class:
@OneToMany(mappedBy = "region", cascade= cascadeType.ALL)
private Set<State> state = new HashSet<>()
And the following ManyToOne mapping in the abstract State class:
@ManyToOne
@JoinColumn(name = "regionId")
private Region region;
but it wouldn't work since State is an unmapped entity. Is there a way I can make a generic mapping of concrete State in the Region class without having to declare each of the concrete classes?
CodePudding user response:
You should change inheritance strategy, I recommend you to use single table strategy, so in my opinion you you should transform your 'State' class to this:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class State implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
@Column(name = "stateCode")
private String code;
@ManyToOne
@JoinColumn(name = "regionId")
private Region region;
}
CodePudding user response:
I think the problem is here:
@OneToMany(mappedBy = "region", cascade= CascadeType.ALL)
private Set<State> state = new HashSet<>();
You could not use @OneToMany association to element of State class cause it's not Entity. You should use a collection of entities that inherits from State class.
I think your code will be fine if you change the code above into that one:
@OneToMany(mappedBy = "region", cascade= CascadeType.ALL)
private Set<StateA> state = new HashSet<>();
