I have a question for designing the ManyToMany in EJB, how can a jointable has a property?
Here is an example, the students and courses are ManyToMany, every student hav
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
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.
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<>();
}