2012-02-11 58 views
5

我在使用QueryDSL创建查询时遇到问题。我想通过它的id检索某个用户的所有组。这是如何工作的?使用QueryDSL JPA编写具有多对多映射的查询

public List<Group> findGroupsByUser(Integer userId) { 
    JPQLQuery query = new JPAQuery(getEntityManager()); 
    ?????? 
    return result; 
} 

映射类:

@Entity(name = "user") 
    public class User { 

    @Id 
    private int id; 
    private String login; 
    @ManyToMany 
    @JoinTable(name = "user2group", joinColumns = @JoinColumn(name = "uid"), inverseJoinColumns = @JoinColumn(name = "gid")) 
    private Set<Group> groups; 
    ... 
} 


@Entity(name = "group") 
public class Group { 

    @Id 
    private int id; 
    private String name; 
    @ManyToMany 
    @JoinTable(name = "user2group", joinColumns = @JoinColumn(name = "uid"), inverseJoinColumns = @JoinColumn(name = "gid")) 
    private Set<User> users; 
    ... 
} 

数据库表:

create table group(
    id int(10) not null auto_increment primary key, 
    name varchar(255) not null, 
    creationdate datetime not null, 
    creator int(10) not null, 
    privacy enum('PUBLIC', 'PRIVATE') not null, 
    constraint foreign key (creator) references user(id) 
) 

create table user2group(
    uid int(10) not null, 
    gid int(10) not null, 
    primary key (uid, gid), 
    constraint foreign key (uid) references user(id), 
    constraint foreign key (gid) references group(id) 
) 

create table user(
    id int(10) not null auto_increment primary key, 
    lastname varchar(50) not null, 
    firstname varchar(50) not null, 
    createdate datetime not null, 
    login varchar(100) unique not null, 
    password varchar(40) not null 
) 
+0

从下面的解决方案工作得很好。组中的用户映射不正确。 @JoinTable(mappedBy = groups) private Set users; – problemzebra 2012-02-20 08:45:29

回答

8

类似下面应该工作

from(user).innerJoin(user.groups, group) 
    .where(user.id.eq(userId)) 
    .list(group); 
+2

在QueryDSL 4.0.8中,将'list()'改为'select()'。 – FuzzY 2016-02-07 23:20:45