[英]Hibernate retrieving parent/children
因此,当我具有一对多的双向关系时,如何确保根据需要从数据库中获取它们?
例如:
在家长班:
@OneToMany(mappedBy="parent")
List<Child> children;
在儿童班:
@ManyToOne
@JoinColumn(name="Parent_Id")
Parent parent;
我只是不确定如何确定当我有父母时,我可以获得其孩子的清单,反之亦然。 不确定Hibernate是如何处理的。
如果要生孩子,我的第一个直觉是:
String hql="FROM Parent WHERE id=:id";
Query query = session.createQuery(hql);
query.setInteger("id", id);
Parent p = (Parent)query.uniqueResult();
List<Child>=p.getChildren();
与此相反:
//insert retrieve child code
Parent p = child.getParent();
我的困惑是,我不确定Hibernate在创建时是否真的在与父母/孩子一起填充对象,如果这样,我不确定是否最有效的方法来检索它们。
关系的每一边都可以配置为渴望或懒惰。 如果渴望的话,Hibernate将在加载包含对象的对象后立即加载该对象。 如果它是惰性的,则Hibernate将放入一个占位符代理对象,并且该代理对象将在您首次访问它时自动加载真实对象(前提是会话/事务仍处于打开状态,否则将抛出LazyInitializationException
)。 无论哪种方式,访问该关系的语法都是相同的p.getChildren()
或child.getParent()
在两种情况下都可以工作。
哪个选项最有效取决于您个人用例的细节。 特别是,相对于加载包含对象的频率,您需要多久一次的关系(惰性使您跳过不必要的加载),多个关系可能会引用一个对象的频率(取决于实现,急于检查数据库表) (即使对象已经加载并在内存中),以及在关闭会话后是否需要访问该关系。
All things depend upon your configuration.If you will apply lazy loading then hibernate internally fetch the record from query at the time of getting the record except its identity.
You can see the
Fetching Strategies
There are four fetching strategies
1. fetch-“join” = Disable the lazy loading, always load all the collections and entities.
2. fetch-“select” (default) = Lazy load all the collections and entities.
3. batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
4. fetch-“subselect” = Group its collection into a sub select statement.
If you want to surety that what is happening internally in hibernate then Please enable
<!--hibernate.cfg.xml -->
<property name="show_sql">true</property>
after enable you can see all queries in console.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.