Search code examples
javajpaone-to-manyrdbmsone-to-one

Model java class as joined result in JPA


Consider the following data. This is a fictional online store system. Surcharge store the surcharge configuration base on different goods category (food or clothing) and payment means (cash or credit card). Packaging store the available packaging option base on the goods category and payment means. If you paid the food by cash, sorry no premium packaging for you.

  • underscore denote primary key.

enter image description here

enter image description here

Surcharge and Packaging is a one-to-many relationship. My situation is, I do not want to have 4 instance of Surcharge object and each has a List<Packaging>. I want to have 7 object and each hold a copy of category, paymentMeans, surcharge, option. Just like as they joined and the result would be 7 rows. How can I model my java class to achieve this? Thank you.

@Entity
@Table(name = "SURCHARGE")
public class Surcharge implements Serializable {

    @EmbeddedId
    private SurchargeId surchargeId;

    @Column(name = "SURCHARGE")
    private int surcharge;

    // how to map this attribute with packaging table as a single instance?
    private Packaging packaging;
}

@Embeddable
public class SurchargeId implements Serializable {

    @Column(name = "CATEGORY")
    private String category;

    @Column(name = "PAYMENT_MEANS")
    private String paymentMeans;

}

@Entity
@Table(name = "PACKAGING")
public class Packaging implements Serializable {

    @EmbeddedId
    private PackagingId packagingId;
}


@Embeddable
public class PackagingId implements Serializable {

    @Column(name = "CATEGORY")
    private String category;

    @Column(name = "PAYMENT_MEANS")
    private String paymentMeans;

    @Column(name = "OPTION")
    private String option;
}


Solution

  • In Surcharge, there will always be a list of Packaging. What you can do is to have one Surcharge object in Packaging. The code will be like below;

    @ManyToOne
    @JoinColumn(name = "CATEGORY", insertable = false, updatable = false)
    @JoinColumn(name = "PAYMENT_MEANS", insertable = false, updatable = false)
    private Surcharge surcharge;
    

    If you don't want that, you can also create a DTO and populate it accordingly using JPQL.