2016-07-27 75 views
0

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

你没有利用JPA的映射。我很确定Spring Data可以用简单的存储库名称来表达你的查询,但即使在JPQL中,你也应该只需要'从事件E中选择e,其中:user in event.participants'(并且传递'User'对象,而不是ID)。 – chrylis

+0

@chrylis,它不起作用 - 从事件E中选择e其中:用户在(event.participants)中 –

+0

Typo(s)。尝试从事件e中选择e,其中:用户在e.participants中。 – chrylis

回答

4
  1. 在你@ManyToMany映射您具备以下条件:

@JoinTable(NAME = “event_user_event”

但在您正在使用的查询user_event。我想其中的一个是错字吗?

  • 在查询

    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" 
    
  • 您使用user_event这不是一个实体(如在异常消息正确地指出)。因此,查询应该如下所示:

    select e 
    from Event e join e.participants u 
    where u.id = :userId and e.startDate > CURRENT_TIMESTAMP 
    

    假设你User实体有一个名为id的属性。此查询应返回与用户:userId关联的所有事件。

    +0

    谢谢兄弟!这样可行! –

    +0

    不客气! – ujulu