I want to model a couple of object relations and I'm currently not sure about a sm开发者_开发百科art way to do this. Let's assume a Record
has a OneToMany relationship to different RecordSources. The common attributes of the RecordSources
are long id
and boolean preferred
. Other attributes are individual and the number of record sources may increase in the future.
One possibility is for Record
@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="record")
private List<GenericSimpleRecordSource> recordSources;
where GenericSimpleRecordSource
would look like this:
@Entity
public class GenericSimpleRecordSource implements Serializable
{
public static enum Type {a,b}
@ManyToOne private Record record;
@NotNull
private Type sourceType;
@OneToOne(cascade = CascadeType.ALL,mappedBy="source")
private SimpleRecordSourceA sourceA;
@OneToOne(cascade = CascadeType.ALL,mappedBy="source")
private SimpleRecordSourceB sourceB;
}
SimpleRecordSourceA
and SimpleRecordSourceA
are individual @Entity
classes. I don't feel comfortable with this approach, using inheritance might be better:
@Entity
@Inheritance(strategy= InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(name="type")
@DiscriminatorValue("generic")
public class GenericRecordSource
{
@Id @GeneratedValue(strategy=GenerationType.AUTO) private long id;
@ManyToOne private Record record;
private boolean preferred;
}
@Entity
@DiscriminatorValue("A")
public class RecordSourceA extends GenericRecordSource
{
...
}
@Entity
@DiscriminatorValue("B")
public class RecordSourceB extends GenericRecordSource
{
...
}
This seems to be smarter, but are there any shortcomings using Inheritance? I appreciate any comments on both approaches or even another alternative.
Is it possible to model the @OneToMany
relationship from Record
like this?
@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="record")
private List<GenericRecordSource> recordSources;
精彩评论