I have a table (product) as follows which holds product related data
@Entity
@Table(name = "product")
public class ProductEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "version")
private String version;
// getters and setter
}
Among some of the products, there are some products which are derived from another product and there is requirement to store this mapping in a table (sub_product_mapping)
@Entity
@Table(name = "sub_product_mapping")
public class SubProductMappingEntity {
@EmbeddedId
private SubProductMappingKeyEntity subProductMappingKeyEntity;
@MapsId("majorProductId")
@ManyToOne
@JoinColumn(name = "major_product_id", referencedColumnName = "id", nullable = false)
private ProductEntity majorProduct;
@MapsId("subProductId")
@ManyToOne
@JoinColumn(name = "sub_product_id", referencedColumnName = "id", nullable = false)
private ProductEntity subProduct;
// getters and setter
and the key entity is as follows
@Embeddable
public class SubProductMappingKeyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "major_product_id", nullable = false)
private int majorProductId;
@Column(name = "sub_product_id", nullable = false)
private int subProductId;
// getters and setters
For a minor product there can only be one major product. But for a major product there can be multiple minor products. Since both the majorProduct and subProduct are instances of ProductEntity, what should be the relationship that should be used? Is it valid to have the relationships as follows?
@MapsId("majorProductId")
@ManyToOne
@JoinColumn(name = "major_product_id", referencedColumnName = "id", nullable = false)
private ProductEntity majorProduct;
@MapsId("subProductId")
@OneToOne
@JoinColumn(name = "sub_product_id", referencedColumnName = "id", nullable = false)
private ProductEntity subProduct;
(note: I am using Hibernate as the JPA implementation)