如何使用HQL通过较弱实体的ID选择更强的实体@MappedSuperclass?

时间:2019-11-26 23:30:58

标签: java hibernate hql

我有以下映射的超类,可作为其他3个类的超类:

@MappedSuperclass
public abstract class Donation {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    //other irrelevant attributes

    @JsonIgnore
    @OneToMany(fetch = FetchType.LAZY)
    private List<Voucher> vouchers;

    //getters and setters
}

Donation扩展的其他类是AdoptionAppointmentExam。这种关系为Voucher创建了以下关联实体:adoption_vouchersappointment_vouchersexam_vouchers

当前的问题是,现在我必须列出所有Voucher及其Donation实体。 由于我没有在凭证类别中指定捐赠关系(因为它可以表示所提及的3个类别中的任何一个,并且我与@MappedSuperclass无关),是否存在使用HQL(检索类似Map<Donation, Voucher>之类的方法)还是为了获取此信息而对我的结构进行细微更改?

1 个答案:

答案 0 :(得分:1)

HQL在以下模型中可能看起来像这样 SELECT a.vouchers FROM Adoption a;

public enum DonationType {
  ADOPTION, APPOINTMENT, EXAM;
}

@MappedSuperclass
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type", 
  discriminatorType = DiscriminatorType.STRING)
public abstract class Donation {
     @Enumerated(EnumType.STRING)
     private DonationType type;

     @JsonIgnore
     @OneToMany(fetch = FetchType.LAZY)
     private List<Voucher> vouchers;
}

@Entity
@DiscriminatorValue(DonationType.ADOPTION)
public class Adoption extends Donation {
}

@Entity
@DiscriminatorValue(DonationType.Exam)
public class Exam extends Donation {
}

@Entity
@DiscriminatorValue(DonationType.APPOINTMENT)
public class Appointment extends Donation {
}

@Entity
public class Voucher {
   //could be single mapping just to supperclass, depends on logic what do you need
   @ManyToOne
   private Adoption adoption;

   @ManyToOne
   private Exam exam;

   @ManyToOne
   private Appointment exam;

}