使用带有多对多映射的QueryDSL JPA编写查询

时间:2012-02-11 17:09:40

标签: java hibernate jpa querydsl

使用QueryDSL创建查询时遇到问题。我想通过其ID检索某个用户的所有组。这是如何运作的?

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
)

1 个答案:

答案 0 :(得分:9)

以下内容应该有效

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