Hibernate OneToOne mapping for different tables
I need to store a data structure that has a value that is string, double, or date.
Is there a way to make a one-to-one mapping conditional on the table?
I tried this ...
@Table(name = "FIELD_CRITERIA")
public class FieldCriteriaEntity implements Identifiable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CRITERIA_KEY", unique = true, nullable = false)
private Long id;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL,optional=true)
@JoinColumn(name="CRITERIA_ID")
private StringCriteriaEntity stringCriteria;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL,optional=true)
@JoinColumn(name="CRITERIA_ID")
private NumeriCriteriaEntity numericCriteria;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL,optional=true)
@JoinColumn(name="CRITERIA_ID")
private DateCriteriaEntity dateCriteria;
}
However, hibernation is not pleasant:
Caused by: org.hibernate.MappingException: Duplicate column on mapping for object:
Is there a way to configure hibernate to do this? Or should I just rewind the FIELD_CRITERIA table to include 3 additional OneToMany relationships?
source to share
First, you can try to make DateCriteriaEntity and NumericCriteriaEntity the owners of the one-to-one relationship rather than the FieldCriteriaEntity. Move the CRITERIA_ID column to the tables corresponding to NumericCriteriaEntity and DateCriteriaEntity so that the column retains the FieldCriteriaEntity as a foreign key and use @OneToMany (mappedBy = "matching field name") on the FieldCriteriaEntity instead of your variant.
Consider this article http://uaihebert.com/jpa-onetoone-unidirectional-and-bidirectional/
source to share
I guess the best way to achieve this is to redesign your entity a bit. See the following class diagram. You can create an abstract CriteriaEntity that will have the criteriaId as the primary key. Please choose your inheritance strategy carefully for your subclasses. If criteria objects are relatively simple, then consider using SINGLE_TABLE, or go to TABLE_PER_CLASS.
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
You will need to rework yours FieldCriteriaEntity
to only use one collation. See the following
@Table(name = "FIELD_CRITERIA")
public class FieldCriteriaEntity implements Identifiable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CRITERIA_KEY", unique = true, nullable = false)
private Long id;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL,optional=true)
@JoinColumn(name="CRITERIA_ID")
private CriteriaEntity criteria;
}
Hope this helps!
source to share