JPA盘点会员

时间:2018-11-30 17:16:44

标签: spring-boot jpa jpql

@Query("select count(s) from S s, TG tg where s.id = :id and tg member of s.tgs and :user member of tg.members")
@Query("select count(s) from S s, TG tg, FG fg where s.id = :id and tg member of s.tgs and :user member of fg.members and fg member of tg.members")
@Query("select count(s) from S s, TG tg, FG fg where s.id = :id and tg member of s.tgs and (:user member of tg.members or :user member of fg.members and fg member of tg.members)")

我在JPA中有3个查询。目标是计算用户是成员的S个实体的数量。 S实体与TG组(直接)和FG组(可以是TG的成员)链接。用户可以是TG或FG的成员。

您可以看到第三个是两个第一个的加法。

两个第一个请求似乎都有效,但是第三个...:

  1. 当我有0个用户时,这3个请求返回0(预期)
  2. 当我在TG中添加用户时,第一个返回1(预期),第二个返回0(预期),第三个返回0(未预期
  3. 当我在TG中的FG中添加用户时,3个请求返回1(不期望,我必须有2个)
  4. 仅当用户在FG中时,第一个请求返回0(预期),其他两个返回1(预期)

我听不懂!!!为什么第三个查询没有返回第一个和第二个查询的结果?

编辑:实体(方案由JPA自动生成)

    @Entity
public class S {

  @Id
  @GeneratedValue
  public long id;

  @ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(joinColumns = @JoinColumn(name = "s_id"), inverseJoinColumns = @JoinColumn(name = "tg_id"))
  private List<TG> tgs = new ArrayList<>();

  (...)

}

@Entity
public class TG extends G {

  @ManyToMany(mappedBy = "tgs", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  private List<S> ss = new ArrayList<>();

  (...)

}


@Entity
public class FG extends G {

  @Column(nullable = false)
  public String uniqueName;

  (...)

}


@Entity(name = "groupe")
public abstract class G extends Subject {

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "membres")
    private Set<Subject> membres = new HashSet<>();

    (...)

}


@Entity
public class U extends Subject {

  @Column(unique = true, nullable = false)
  public String uniqueName;

  (...)

}


@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Subject {

  @Id
  @GeneratedValue
  public long id;

  (...)

}

0 个答案:

没有答案