当 fetch=FetchType.LAZY 时 Hibernate 断开代理

发布于 2024-10-07 16:37:51 字数 509 浏览 5 评论 0原文

@Entity
public class Master implements Serializable{
private List slaves;
@OneToMany(mappedBy = "Master",fetch=FetchType.LAZY)
public List getSlaves() {
   return slaves;
}
}

I want this code to pass.

List m = createQuery("from Master where id=1").getResultList();
for (Master master : m) {
    assertNull(master.getSlaves());
}

我希望 getSlaves() 返回 null 并且不初始化代理来连接到数据库(该主服务器有从服务器,我不想从数据库中删除它们)。

在 Hibernate 或 JPA 中有什么办法可以做到这一点吗?

当 fetch 是 EAGER 时,还有办法做到这一点吗?

@Entity
public class Master implements Serializable{
private List slaves;
@OneToMany(mappedBy = "Master",fetch=FetchType.LAZY)
public List getSlaves() {
   return slaves;
}
}

I want this code to pass.

List m = createQuery("from Master where id=1").getResultList();
for (Master master : m) {
    assertNull(master.getSlaves());
}

I want getSlaves() to return null and not to initialize a proxy to connect to the database(this master has slaves and I dont want to delete them from database).

Is there any way to do that in Hibernate or JPA?

Is there also way of doing that when fetch is EAGER?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒中人 2024-10-14 16:37:51

默默地失败的代理调试起来会很棘手。

看到 hibernate 的代码后,我认为您没有配置它的选项。您可以尝试反射性调用collection.setInitialized()来伪初始化集合,但这会很丑陋。

Silently failing proxies would be a tricky thing to debug.

After seeing the code of hibernate, I don't think you have an option to configure that. You can try to reflectively call collection.setInitialized(), to pseudo-initialize the collection, but that'd be ugly.

小嗲 2024-10-14 16:37:51

如果我理解正确的话,您希望一个实际上有从属的主设备无论如何都为从属列表返回一个空值?这是在测试环境中吗?您确定这就是您想要的,并且您走在正确的道路上吗?

另一种丑陋的方法是直接将奴隶列表显式设置为空。这将确保只要您在同一个会话中, getSlaves() 返回 null,但数据库中实际上不会更改任何内容(至少对于 hibernate 而言)。这种方法也适用于急切的收藏。

If I understand you correctly, you want a master that actually HAS slaves to return a null value for the list of slaves anyhow? Is this in a test context? Are you sure that this is what you want, and that you are on the right track?

Another ugly approach is to just set the list of slaves to null explicitly. This will ensure that getSlaves() returns null as long as you are in the same session, but nothing will actually be changed in the database (at least for hibernate). This approach works also for an eager collection.

绿萝 2024-10-14 16:37:51

对 Collection 的 get 不应返回 null。您正在通过让代码返回 null 来设置陷阱。

而是让它返回一个空集并断言该集是空的

assertTrue(master.getSlaves().size() == 0);

A get on a Collection should not return null. You're setting a booby trap in your code by having it return null.

Rather have it return an empty set and assert that the set is empty

assertTrue(master.getSlaves().size() == 0);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文