JPA ManyToMany, how can JoinTable have a property?

时间秒杀一切 提交于 2019-11-30 09:10:51

It is not possible, you cannot add property to relationship. If you need to access property in the join table, then that property belongs to some entity and as a result you need third entity.

It is possible.

You just need to replace many-to-many mapping with the explicit combination of one-to-many and many-to-one mappings via a 3rd entity, that would represent the association between the two primary entities (student and course in your example).

Please read details here

Entities with Many to Many Relationships (Merchant and Service). This can be achieved using a third entity as follow:-

@Entity
@Table(name = "merchant")
public class Merchant implements java.io.Serializable {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.merchant",targetEntity = MerchantService.class)
    private Set<MerchantService> merchantServices = new HashSet<>();
}

@Entity
@Table(name = "merchant_service")
@AssociationOverrides({
        @AssociationOverride(name = "pk.merchant",
            joinColumns = @JoinColumn(name = "merchant_id")),
        @AssociationOverride(name = "pk.service",
            joinColumns = @JoinColumn(name = "service_id")) })
public class MerchantService implements java.io.Serializable {

    @EmbeddedId
    private MerchantServiceId pk = new MerchantServiceId();

    private boolean isActive;

    public MerchantServiceId getPk() {
        return pk;
    }

    public void setPk(MerchantServiceId pk) {
        this.pk = pk;
    }

    @Transient
    public Service getService() {
        return getPk().getService();
    }


    @Transient
    public Merchant getMerchant() {
        return getPk().getMerchant();
    }


    public boolean isActive() {
        return isActive;
    }

    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }

}

@Embeddable
public class MerchantServiceId implements java.io.Serializable {

    private Merchant merchant;
    private Service service;

    @ManyToOne
    public Merchant getMerchant() {
        return merchant;
    }

    @ManyToOne
    public Service getService() {
        return service;
    }

}

@Entity
@Table(name = "service")
public class Service implements java.io.Serializable {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.service",targetEntity = MerchantService.class)
    private Set<MerchantService> merchantServices = new HashSet<>();

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!