Question

I have a problem with using QueryDSL to create a query. I want to retrieve all groups of a certain user by its id. How does this works?

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

Mapped classes:

@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;
    ...
}

Database tables:

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
)
Was it helpful?

Solution

Something like the following should work

from(user).innerJoin(user.groups, group)
  .where(user.id.eq(userId))
  .list(group);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top