Reputation: 535
I have a Abstract class product and three sub classes Honey, Wax and Misc. As per definition, the sub classes extend the Product class and add few extra fields. I am using the JPA annotations to perform the mappings. The classes are given below.
Product.java
@MappedSuperclass
public abstract class Product implements Comparable<Product> {
private static long currentId =1;
@Id
@Column(name="ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@Column(name="price")
private double price; // in euro, internationalization can come later
protected String productType;
Honey.java
@Entity
public class Honey extends Product {
@Column(name="expiryDate")
private Date expiryDate;
@ManyToOne
@JoinColumn(name="source")
private Flower source;
Wax.java
import javax.persistence.Entity;
@Entity
public class Wax extends Product {
Miscellaneous.java
@Entity
public class Miscellaneous extends Product {
@Column(name="expireDate")
private Date expireDate;
@Column(name="areaOfApplication")
private String areaOfApplication;
The result is that I have three different tables created in the DB. But my question is that if I want to get all the available products, then my guess is that I will have to query three different tables. This approach does not seem right to me. Shouldn't the right approach be that I should have a product table, where all the products are listed? but then each product can be of different category (honey, wax or Misc), which means different columns and can contain null values.
Can someone please enlighten me on this? Thanks a lot.
Upvotes: 0
Views: 3226
Reputation: 1053
Changing your MappedSuperclass to an abstract entity defining a proper inheritance strategy should do the trick. In your case single table with a discriminator column would be the right inheritance choice. You should even be able to query the abstract superclass in order to get all matching subclass in the resultset.
Upvotes: 1