假设我们有以下情况:父母有一个孩子的列表,而每个孩子都是“数字”或“字母”类型,我想选择其中的父母
我有以下最小的例子,我已经解决了第一个案例但不知道第二个案例,因为我认为我必须按对象类型进行过滤,我不确定这是否可行仅通过SQL (我希望不要在Java中过滤以尽早减少有问题的实体数量。)
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
@Entity
@NamedQueries({
@NamedQuery(name = "findWithNumberChildrenContainingNumber42", query = "SELECT nc.parent from NumberChild nc WHERE nc.number = 42"),
@NamedQuery(name = "findWithoutNumberChildren", query = "?")
})
public class Parent implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "parent")
private List<Child> children;
// ...
}
import java.io.Serializable;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
abstract class Child implements Serializable {
@ManyToOne
private Parent parent;
// ...
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class NumberChild extends Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Integer number;
// ...
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class AlphabetChild extends Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String alphabet;
// ...
}
答案 0 :(得分:1)
原来以前的查询比必要的更复杂,所以这是我刚刚测试过的。
SELECT p FROM Parent p WHERE p NOT IN (SELECT nc.parent FROM NumberChild nc)
嗯,在我的测试中,名称不同,但Hibernate的日志显示它确实产生了更有效的查询。