gpt4 book ai didi

java - Spring /hibernate : EntityManager multiplies instances

转载 作者:行者123 更新时间:2023-12-02 05:38:57 26 4
gpt4 key购买 nike

我正在尝试从 id 列表中返回 Hibernate 实体列表。以下代码负责:

String sql = "select id from foo where some condition is met";
List<Long> ids = jdbcTemplate.queryForList(sql, Long.class); // 3 ids ..
List<FooEntity> list = ((Session) this.entityManager.getDelegate())
.createCriteria(FooEntity.class)
.add(Restrictions.in("id", ids)).list(); // .. -> 60 entities

...

@Entity
public class FooEntity implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;

@OneToMany(
targetEntity = BarEntity.class,
cascade = { CascadeType.ALL },
fetch = FetchType.EAGER)
@JoinTable(
name = "foo_bar",
joinColumns = @JoinColumn(name = "foo_id"),
inverseJoinColumns = @JoinColumn(name = "bar_id"))
private List<BarEntity> bars;

...
}

当代码执行后,我有一个包含 3 个 id 的列表和一个包含 60 个 FooEntity 实例的列表!

在正常情况下,我希望这些代码行能够传递与 id 一样多的实体。有什么想法可能导致这种奇怪的行为吗?

编辑:根据下面 Thomas 的评论,我发现每个 Foo 实体正好有 20 个 Bar 实例。并且每个 FooEntity 也返回 20 倍。

最佳答案

默认情况下,Hibernate 不会从结果列表中删除重复项,除非您放置 distinct(foo)在查询中。因此,您将在列表中获得 60 个条目 3 FooEntity以 20 BarEntity 连接的实例每个实例,只是因为 JDBC 结果集将有 60 行。

所以添加 distinct查询的谓词(看看这里: How to get distinct results in hibernate with joins and row-based limiting (paging)? )或使用 new LinkedHashSet<FooEntity>( list )如果FooEntity有一个有意义的实现 equals()hashCode() (我不依赖默认实现,因为在某些情况下,Hibernate 可能会创建同一实体的多个实例,这会导致“这破坏了 == 语义”消息)。

关于java - Spring /hibernate : EntityManager multiplies instances,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24680688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com