【问题标题】:Writing a query with QueryDSL JPA with many to many mapping使用具有多对多映射的 QueryDSL JPA 编写查询
【发布时间】:2012-02-11 17:09:40
【问题描述】:

我在使用 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
)

【问题讨论】:

  • 下面的解决方案运行良好。组中的用户未正确映射。 @JoinTable(mappedBy=groups) 私有 Set 用户;

标签: java hibernate jpa querydsl


【解决方案1】:

类似下面的东西应该可以工作

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

【讨论】:

  • 在 QueryDSL 4.0.8 中,将 list() 更改为 select()
猜你喜欢
  • 2014-07-23
  • 2012-12-08
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多