我有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