【问题标题】:Getting duplicate result objects in @ManyToMany relationship with Hibernate/JPA and play framework在与 Hibernate/JPA 和播放框架的@ManyToMany 关系中获取重复的结果对象
【发布时间】:2013-03-13 20:07:19
【问题描述】:

我正在使用 Play Framework v1.2.5 以及 JPA 和 Hibernate。

我有 2 个模型:

@Entity
public class MapTile extends Model {

    // ...

    @Required
    public Integer tileOrder;

    @Required
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    public List<MapBuildingInfo> buildingsInfo;

    // ...
}

@Entity
public class MapBuildingInfo extends Model {

    // ...

    @Required
    public Integer buildingsCount;

    // ...
}

假设我有以下数据:

MapTile :
    tileOrder: 1
    buildingsInfo: 
        - buildingsCount : 1
        - buildingsCount : 2

MapTile :
    tileOrder: 2
    buildingsInfo: 
        - buildingsCount : 3
        - buildingsCount : 4

我正在尝试检索(只有一个查询和连接)所有 MapTiles 及其对应的 MapBuildingInfos

这是我使用的查询:

List<MapTile> list = MapTile.find("from MapTile tile left join fetch tile.buildingsInfo building").fetch();

这是我列表中的结果:

list[0].tileOrder => 1
list[0].buildingsInfo[0].buildingsCount => 1
list[0].buildingsInfo[0].buildingsCount => 2

list[1].tileOrder => 1
list[1].buildingsInfo[0].buildingsCount => 1
list[1].buildingsInfo[0].buildingsCount => 2

list[2].tileOrder => 2
list[2].buildingsInfo[0].buildingsCount => 3
list[2].buildingsInfo[0].buildingsCount => 4

list[3].tileOrder => 2
list[3].buildingsInfo[0].buildingsCount => 3
list[3].buildingsInfo[0].buildingsCount => 4

而不仅仅是:

list[0].tileOrder => 1
list[0].buildingsInfo[0].buildingsCount => 1
list[0].buildingsInfo[0].buildingsCount => 2

list[1].tileOrder => 2
list[1].buildingsInfo[0].buildingsCount => 3
list[1].buildingsInfo[0].buildingsCount => 4

Hibernate/JPA 似乎将每个结果放入一个新的 MapTile 对象中,因此它创建了一个重复项。但是他正确填写了MapTilebuildingsInfo

我不明白为什么我会得到这个结果。你知道我做错了什么吗?你知道这是否是 Hibernate/JPA 的错误吗?还是我的错误?我怎样才能得到正确的结果?

感谢您的帮助!

【问题讨论】:

    标签: hibernate jpa playframework


    【解决方案1】:

    我认为您必须将查询转换为:

    select distinct tile from MapTile tile left join fetch tile.buildingsInfo building

    由于您的 fetch 您创建了多行,您需要告诉 hibernate 将其映射到同一个实例。

    【讨论】:

    • 感谢您的回答,它似乎有效!没想到这么简单
    • @FabienHenon 谢谢,它总是有帮助。
    猜你喜欢
    • 2019-03-29
    • 1970-01-01
    • 2015-01-18
    • 2011-09-09
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多