我有2個實體:用戶和事件。每個映射到適當的表。另外我有第三張表user_event
,因爲這兩個實體有多對多的關係。我需要從數據庫中選擇其中用戶參與的所有事件Spring Data ManyToMany select query
事件:
@Entity
@Table(name = "event")
public class Event extends AbstractPersistable<Long> {
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "user_event",
joinColumns = @JoinColumn(name = "event_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
private Collection<User> participants;
用戶:
@Entity
@Table(name = "user")
public class User extends AbstractPersistable<Long> {
private String nickname;
user_event
表不具有在Java代碼中的實體。我想這個查詢:
@Query("select e from Event e join user_event ue on ue.event_id = e.id where ue.user_id = :userId and e.startDate > CURRENT_TIMESTAMP")
Page<Event> findAllForUser(Pageable pageable, @Param("userId") Long userId);
但在應用程序啓動此查詢原因的異常:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [select e from Event e join user_event ue on ue.event_id = e.id where ue.user_id = :userId and e.startDate > CURRENT_TIMESTAMP]
在MySQL Workbench中我會嘗試這樣的:
select * from event e join user_event ue on e.id = ue.event_id where ue.user_id = 1 and e.startDate > now();
和它的作品。但是如何爲spring數據創建良好的工作查詢?
SQL轉儲:
select count(event0_.id) as col_0_0_ from event event0_ inner join address address1_ on event0_.address_id=address1_.id
cross join user_event participan2_, user user3_ where event0_.id=participan2_.event_id and participan2_.user_id=user3_.id
and (? in (.)) and event0_.startDate>CURRENT_TIMESTAMP
你沒有利用JPA的映射。我很確定Spring Data可以用簡單的存儲庫名稱來表達你的查詢,但即使在JPQL中,你也應該只需要'從事件E中選擇e,其中:user in event.participants'(並且傳遞'User'對象,而不是ID)。 – chrylis
@chrylis,它不起作用 - 從事件E中選擇e其中:用戶在(event.participants)中 –
Typo(s)。嘗試從事件e中選擇e,其中:用戶在e.participants中。 – chrylis