【问题标题】:Many to many - select collection of entities without determined field and with limited number of results多对多 - 选择没有确定字段且结果数量有限的实体集合
【发布时间】:2016-09-04 19:28:28
【问题描述】:

我有两个存在多对多关系的实体类

@Entity
public class User implements Serializable {
    ...

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "members")
    private Set<Group> groups = new HashSet<>();

}

@Entity
public class Group implements Serializable {
  ...

  @JoinTable(name = "user_groups",
          joinColumns = {@JoinColumn(name = "group_id")},
          inverseJoinColumns = {@JoinColumn(name = "user_id")})

  private Set<User> members = new HashSet<>();

}

当我请求获取特定组时,我得到:

{
  "id": 12,
  "adminId": 12345,
  "name": "name",
  "category": "cat",
  "city": "city",
  "members": [
    { 
      "id": 1,
      "firstName": "SomeName",
      "birthday": 802476000000,
      "city": "SomeCity",
      "country": "SomeCountry",
      "age": 21,
      "groups": [
        {
          "id": 1,
          "adminId": 123,
          "name": "Some group name",
          "category": "some category",
          "city": "some city"
        }
      ],
      "picturePath": some path
    }
]

} 当我想通过 id 获取特定组时,在其成员字段中,我希望只有没有组字段的用户和数据库中的前 100 行。 希望您理解:用户属于多个组,组有很多用户

我想得到这样的东西:

{
  "id": 12,
  "adminId": 12345,
  "name": "name",
  "category": "cat",
  "city": "city",
  "members": [
    { 
      "id": 1,
      "firstName": "SomeName",
      "birthday": 802476000000,
      "city": "SomeCity",
      "country": "SomeCountry",
      "age": 21,
      "picturePath": some path
    }
]

我想到的是创建连接表的实体类(具有列:user_id,group_id)并创建查询,该查询将获取给定 group_id 的 user_ids 的结果,然后循环获取具有我感兴趣的字段的用户在

也许我应该使用一些元组查询? 感谢您花时间解决我的问题

【问题讨论】:

    标签: java mysql hibernate jpa many-to-many


    【解决方案1】:

    哦,愚蠢的我:)

    Query query = entityManager.createNativeQuery("SELECT u.user_id,u.birthdate,u.first_name,u.city,u.country,u.age,u.picture_path " +
                    "FROM users u " +
                    "INNER JOIN user_groups ug " +
                    "ON ug.user_id = u.user_id WHERE ug.group_id = ?",User.class);
    

    user_groups 是一个连接表,可以使用 LIMIT 来计算结果(在 MySQL 中)

    【讨论】:

      猜你喜欢
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多