Hibernate:一对一延迟加载,可选 = false [英] Hibernate: one-to-one lazy loading, optional = false

查看:20
本文介绍了Hibernate:一对一延迟加载,可选 = false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一对一延迟加载在休眠中不起作用的问题.我已经解决了,但仍然正确理解会发生什么.

I faced the problem that one-to-one lazy loading doesn't work in hibernate. I've already solved it, but still don't properly understand what happens.

我的代码(延迟加载在这里不起作用,当我拉人 - 地址也被提取):

My code (lazy loading doesn't work here, when I pull Person - Address is also fetched):

@Entity
public class Person{

  @Id
  @SequenceGenerator(name = "person_sequence", sequenceName = "sq_person")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "person_sequence")
  @Column(name = "id")
  private long personID;

  @OneToOne(mappedBy="person", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
  private Adress address;
  //.. getters, setters
}

@Entity
public class Address {

  @Id
  @Column(name="id", unique=true, nullable=false)
  @GeneratedValue(generator="gen")
  @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="person"))
  private long personID;

  @PrimaryKeyJoinColumn
  @OneToOne
  private FileInfo person;
}

但是:如果我在 OneToOne 关系中添加 optional=false,延迟加载工作正常!>

But: if I add optional=false in OneToOne relationship, lazy loading works fine!

@OneToOne(mappedBy="person", cascade=CascadeType.ALL, optional = false, fetch = FetchType.LAZY)
private Adress address;

问题/恳求:请向我解释 optional=false 注释如何帮助实现延迟加载.

Question/Entreaty: please, explain to me how optional=false annotation helps to achieve lazy loading.

PS 我读过帖子 post1post2,明白为什么简单的OneToOne不能偷懒,但我还是可以不要掌握 optional=false 魔法.

P.S. I've read posts post1 and post2, and understand why simple OneToOne can't be lazy, but I still can't grasp optional=false magic.

推荐答案

如果关联是可选的,则 Hibernate 无法在不发出查询的情况下知道给定人员的地址是否存在.所以它不能用代理填充地址字段,因为可能没有引用这个人的地址,也不能用 null 填充它,因为可能有一个引用这个人的地址.

If the association is optional, Hibernate has no way of knowing if an address exists for a given person without issuing a query. So it can't populate the address field with a proxy, because there could be no address referencing the person, and it can't populate it with null, because there might be an address referencing the person.

当您强制关联(即 optional=false)时,它会信任您并假定地址存在,因为关联是强制性的.所以它直接用代理填充地址字段,知道有一个地址引用了这个人.

When you make the association mandatory (i.e. optional=false), it trusts you and assumes that an address exists, since the association is mandatory. So it directly populates the address field with a proxy, knowing that there is an address referencing the person.

这篇关于Hibernate:一对一延迟加载,可选 = false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆