且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

@ManyToOne(fetch = FetchType.LAZY)在非主键引用列上不起作用

更新时间:2023-01-09 21:20:48

看到与Hibernate 5.0.4完全相同的行为.如果连接列是主键,则@ManyToOne(带有互为OneToMany)和Lazy的提取将完美工作.如果不是,则延迟加载会中断,并且每次实例化对象时,Hibernate都会急切地获取所有ManyToOne.如果对1000条记录执行Criteria.list(),这可能会非常慢.最初是对1000条记录的单个查询,现在可以膨胀为5000条查询,以使用单个选择热切地获取各种@ManyToOne.

Seeing the exact same behaviour with Hibernate 5.0.4. @ManyToOne (with a reciprocal OneToMany) and Lazy fetching works perfectly if the join column is the primary key. If it's not, lazy loading breaks and Hibernate eagerly fetches all ManyToOne's every time an object is instantiated. This can be catastrophically slow if you do a Criteria.list() for, say, 1000 records. What started out as a single query for 1000 records can balloon into 5000 queries to eagerly fetch a variety of @ManyToOne's using individual selects.

绝对没有我能够测试/更改的内容以任何方式对此进行解释,并且我可以可靠地重现它.

Absolutely nothing I've been able to test/change has explained this in any way and I can reproduce it reliably.

我必须在使用非PK进行连接的应用程序中实现的解决方案是仅丢弃@ManyToOne/@OneToMany注释对,并手动编写集合提取操作(使用瞬态变量缓存结果).这样做的工作量更大,但考虑到我的一些对象有5或6个@ManyToOne对象,并且所有这些都由Hibernate急切地通过单个选择来获取,因此性能要高得多.

The solution I had to implement in my app that uses non-PK's for joins was to just trash @ManyToOne/@OneToMany annotation pairs and write collection fetches manually (caching the results with a transient variable). It's way more work but the performance is substantially higher given that some of my objects have 5 or 6 @ManyToOne objects and all of these were being eagerly fetched with individual selects by Hibernate.

不幸的是,我无法重新组织架构以适应Hibernate中的这个怪癖.我正在做一个涉及Heroku Connect的项目,当使用非主键的表中的"sfid"列完成来自Salesforce.com的数据合并时,表之间的联接.主键是Heroku Postgres数据库中记录唯一的一个单独值,不能用于进行联接,因为数据库中没有其他表引用此主键.

Unfortunately, I can't reorganize my schema to accommodate this quirk in Hibernate. I'm doing a project involving Heroku Connect and the joins between tables when merging data from Salesforce.com are done using a "sfid" column in the table that is not the primary key. The primary key is a separate value unique to the record in the Heroku Postgres database and can't be used to do joins on as no other tables in the database refer to this primary key.

我假设这是Hibernate中的错误;我所读或能够修改的任何内容都没有以任何方式影响此行为,并且正如我提到的,如果连接列是主键,我可以使系统完全按预期工作.

I'm assuming that this is a bug in Hibernate; nothing I've read or been able to modify has affected this behaviour in any way and, as I mentioned, I can make the system work exactly as expected if the join columns are the primary keys.