0

我使用单表策略(带鉴别器)来使用继承

UML 架构 => http://yuml.me/67acf6a6

我想获取具有所有相关关联(汽车、书籍和电视)的客户的所有订单。你知道如何在不破坏模型类的情况下实现这一点。

@Entity
@Table(name = "customers")
public class Customer{
  private Date birthDate;
  private String name;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "customer", cascade = CascadeType.ALL, orphanRemoval = true)
  @OrderBy("order")
  private List<? extends Order> orders;
}

@Entity
@Table(name = "orders")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public abstract class Order{

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @NotNull
    @JoinColumn(name = "CustomerID")
    private Customer customer;
}


@Entity
@DiscriminatorValue("book")
public class BookOrder extends Order {

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name="book_id")
  private Set<Book> books;
}

@Entity
@DiscriminatorValue("car")
public class CarOrder extends Order {

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name="car_id")
  private Set<Car> cars;
}

@Entity
@DiscriminatorValue("tv")
public class TvOrder extends Order {
  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name="tv_id")
  private Set<Tv> tvs; 
}

如果我在做 HQL

select cutomer from customer customer
inner join fetch customer.orders order
left join fetch order.cars
left join fetch order.books
left join fetch order.tvs

我收到错误

org.hibernate.QueryException: could not resolve property: cars, 

在抽象类 Order 中有意义,该字段不存在。

你知道我怎么能做到这一点吗?在这种情况下,休眠的建议是什么?

我的目标是简单的查询并获取所有内容。

4

1 回答 1

0

如果您执行以下查询

select c from customer c
join fetch c.orders

然后您检索所有具有任何类型订单(汽车 | 书籍 | 电视)的客户。这些订单是多态的,如果instanceof对每个 Customer.orders 元素都这样做,您可以确定订单元素的类型。

于 2013-07-18T15:11:48.517 回答