SQL到JPQL,如何查询嵌套的JPQL

时间:2018-10-15 07:02:48

标签: spring jpa jpql

我想知道JPQL是否可以嵌套查询。我正在研究Spring Data JPA,并且还上传了一些相关问题。

如果我在MySQL中使用sql以下的代码,该如何生成JPQL:

select
    c.*
from
    cheat c
    left join (select * from cheat_vote where val = 1) v on c.cheat_seq = v.cheat_fk
group by
    c.cheat_seq
having
    count(*) < 10
limit 5

我有两个实体。

public class Cheat implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cheat_seq", length = 10)
    private Long cheatSeq;

    @Column(name = "question", unique = true, nullable = false)
    private String question;

    @Column(name = "answer", unique = true, nullable = false)
    private String answer;

    @Column(name = "writer_ip", nullable = false)
    private String writerIP;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "reg_date", nullable = false)
    private Date regDate;

    @Transient
    private String regDateText;

    @OneToMany(mappedBy = "cheat", fetch=FetchType.LAZY)
    private Set<CheatVote> vote;

    @Override
    public String toString() {
        return "Cheat [cheatSeq=" + cheatSeq + "]";
    }


}

上面的实体有一个@OneToMany集合,该集合实体在下面。

public class CheatVote implements Serializable{

    private static final long serialVersionUID = 1L;

    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Id
    @Column(name="seq", nullable=false)
    private Long seq;

    @Column(name="val", nullable=false)
    @NonNull
    private Integer value;

    @Column(name="ip_address", nullable=false)
    @NonNull
    private String ipAddress;

    @JoinColumn(name="cheat_fk", referencedColumnName="cheat_seq")
    @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    @NonNull
    private Cheat cheat;

    @Override
    public String toString() {
        return "CheatVote [seq=" + seq + "]";
    }


}

我想获得包含少于10个子代CheatVote实体的Cheat实体。

1 个答案:

答案 0 :(得分:0)

您可以尝试:

@Query("SELECT c FROM Cheat c LEFT JOIN c.vote v WHERE v.value = 1 GROUP BY c.cheatSeq HAVING count(c) < 10")

关于'LIMIT',您可以使用Spring Data JPA的参数Pageable