简体   繁体   English

单向OneToMany的JPQL

[英]JPQL for a Unidirectional OneToMany

I need a jpql query for my Spring repository interface method, to retrieve all Posts for a given Semester. 我需要一个针对Spring存储库接口方法的jpql查询,以检索给定学期的所有帖子。

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.MERGE)
@JoinTable
(
 name = "semester_post",
 joinColumns = {@JoinColumn(name = "semester_id", referencedColumnName = "id")},
 inverseJoinColumns = {@JoinColumn(name = "post_id", referencedColumnName = "id", unique = true)}
)
private List<PostEntity<?>> posts = new ArrayList<>();

PostEntity doesn't have a reference to Semester, and I do not want to add one, because I plan to use this PostEntity for other things than Semester. PostEntity没有对Semester的引用,我也不想添加一个,因为我打算将这个PostEntity用于其他事情而不是学期。 Maybe I'll have another class (let's say Group) which will also have a OneToMany of PostEntity (like the one in Semester) 也许我会有另一个班级(比如说Group)也会有一个PostTntMany的OneToMany(就像学期一样)

So, how do I write this SQL query as a JPQL one ? 那么,我如何将这个SQL查询编写为JPQL呢?

select * from posts join semester_post on semester_post.post_id = posts.id where semester_post.semester_id = 1;

My repository 我的存储库

public interface PostRepository extends JpaRepository<PostEntity, Long> {

String QUERY = "SELECT p FROM PostEntity p ... where semester = :semesterId";

@Query(MY_QUERY)
public List<PostEntity> findBySemesterOrderByModifiedDateDesc(@Param("semesterId") Long semesterId);

A query which will get you the result that you need is: 一个可以获得所需结果的查询是:

SELECT p FROM SemesterEntity s JOIN s.posts p WHERE s.id = :semesterId

This query uses the JOIN operator to join the SemesterEntity to the PostEntity across the posts relationship. 此查询使用JOIN运算符跨posts关系将SemesterEntity连接到PostEntity By joining the two entities together, this query returns all of the PostEntity instances associated with the relevant SemesterEntity . 通过将两个实体连接在一起,此查询将返回与相关SemesterEntity关联的所有PostEntity实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM