Hibernate:ManyToOne关系,只加载一次关系 [英] Hibernate: ManyToOne Relation, Load Many relation Only Once

查看:94
本文介绍了Hibernate:ManyToOne关系,只加载一次关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Hibernate 5.2和Java 8
我有一个名为PatientMetaData的表,它具有followng字段(在数据库表本身中,hmo是一个整数):

  @Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int uid;
私人字符串名称;
@ManyToOne
@JoinColumn(name =hmo)
私人Hmo hmo;

Hmo表包含一个uid和一个名称:

  @Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int uid;
私人字符串名称;

并且通过hmo表中的uid和患者表中的hmo与患者表相关。 p>

在加载所有患者时,我发现对于每个患者,都有一个关于其HMO的查询。

但是,有10K个患者和仅7个HMO,所以为每个病人加载HMO似乎是多余的。

我有一种方法可以避免所有这些查询吗?



一种选择是定义 PatientMetadata 实体类将hmo作为一个整数,因此我只会加载患者,然后将所有HMO加载到Java映射中,最后,我将从语法上附加一个HMO每个病人的地图。

这看起来有点麻烦。

有没有更好的方式直接使用Hibernate?

解决方案

当在@ManyToOne上使用懒惰提取时,Hibernate会有一些好奇的行为,所以这可能不起作用。 b $ b

我推荐使用@BatchSize(2个可能的位置根据你如何检索你的病人,你也可以通过JPA中的root.fetch()来获取Hmos。HBA类或者病人与病人的关系)标准查询,这样HMos就会被加载一个左连接。



解决方法实际上是一种黑客入侵,应该避免。


Using Hibernate 5.2 and Java 8 I have a table named PatientMetaData which has the followng fields (in the DB table itself, hmo is an integer):

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int uid;
private String name;
@ManyToOne
@JoinColumn(name="hmo")
private Hmo hmo;

The Hmo table contains a uid and a name:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int uid;
private String name;

and is related to the patients table through the uid in hmo table and hmo in patients table.

When loading all the patients, I see that for each patient, there is a query for its HMO.
However there 10K patients and only 7 HMOs, so it seems redundant to load the HMO for each patient.
I there a way to avoid all these queries?

One option is to define the PatientMetadata entity class to have the hmo as an integer so I will only load the patients, then load all the HMOs into a Java map, and finally I will grammatically attach an HMO from the map to each patient.

This looks a little cumbersome.
Is there a better way of doing so directly with Hibernate?

解决方案

Hibernate has curious behavior when using lazy fetch on a @ManyToOne, so this will probably not work.

I recommend using @BatchSize (2 possible positions, on Hmo class or on the relation in the patient).

Depending on how you retrieve your patients, you can also fetch Hmos via root.fetch() in JPA criteria queries, so that HMos get loaded with a left join.

The workaround is really a hack imo and should be avoided.

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

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