JPA @NamedQuery由@OneToMany对象类型

时间:2016-10-13 13:46:27

标签: java jpa one-to-many jql

假设我们有以下情况:父母有一个孩子的列表,而每个孩子都是“数字”或“字母”类型,我想选择其中的父母

  • 有一个或多个“数字”等于42的“数字”儿童
  • 根本没有“数字”儿童(但可能有“字母”儿童)

我有以下最小的例子,我已经解决了第一个案例但不知道第二个案例,因为我认为我必须按对象类型进行过滤,我不确定这是否可行仅通过SQL (我希望不要在Java中过滤以尽早减少有问题的实体数量。)

Parent.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;

    // ...
}

Child.java

import java.io.Serializable;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
abstract class Child implements Serializable {

    @ManyToOne
    private Parent parent;

    // ...
}

NumberChild.java

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;

    // ...  
}

AlphabetChild.java

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;

    // ...
}

1 个答案:

答案 0 :(得分:1)

原来以前的查询比必要的更复杂,所以这是我刚刚测试过的。

SELECT p FROM Parent p WHERE p NOT IN (SELECT nc.parent FROM NumberChild nc)

嗯,在我的测试中,名称不同,但Hibernate的日志显示它确实产生了更有效的查询。