[英]Spring Data JPA get entity foreign key without causing the dependent entity lazy load
I have an @Entity
A that references another entity B using OneToOne relation ship. 我有一个
@Entity
A,它使用OneToOne关系船引用了另一个实体B。 I fetch entity A using spring data JpaRepository 我使用弹簧数据JpaRepository获取实体A
A a = aRepository.findById(1);
int b_id = a.getB().getId();
As you can see I need to query ID of the B table, however in order to do that, I need to call getter of the B table, which will cause lazy-loading the B table itself. 如您所见,我需要查询B表的ID,但是为此,我需要调用B表的getter,这将导致B表本身的延迟加载。 I do not want to do that because the only thing I need is the get ID, nothing else, and that ID is present in the first A table.
我不想这样做,因为我唯一需要的就是获取ID,别无其他,并且该ID存在于第一个A表中。
Is there any trick that will help me to get ID of the dependent table without triggering new query? 有什么技巧可以帮助我在不触发新查询的情况下获取依赖表的ID?
UPDATE UPDATE
@Entity
class A {
@Id
private Long id;
@OneToOne
private B b;
}
@Entity
class {
@Id
private Long id;
}
Without looking at the entity mapping, I suspect, your entity classes might be using hibernate annotations on the field
. 我怀疑,如果不查看实体映射,您的实体类可能
hibernate annotations on the field
使用了hibernate annotations on the field
。 With this if you call even the getId() method as in a.getB().getId()
on the entity it will result in initializing the proxy (ie, B object) and hits the database to fetch it. 这样,即使您像在实体上的
a.getB().getId()
那样调用getId()方法,也会导致初始化代理(即B对象)并访问数据库以获取它。
So if the intent is only to get the id
of the entity you can place the hibernate annotations on the getter methods
instead. 因此,如果仅是获取实体的
id
,则可以将休眠annotations on the getter methods
。 This doesn't result initializing the proxy (B object) to return the id
. 这不会初始化代理(B对象)以返回
id
。 Although accessing any property other than id will result in hitting the database. 尽管访问除id以外的任何属性都将导致命中数据库。
Have a look at related bug at HHH-3718 看看HHH-3718的相关错误
So, try using property/getter AccessType instead of field access. 因此,请尝试使用属性/获取器AccessType而不是字段访问。 As an example instead of placing the annotations on field
作为示例,而不是将注释放在字段上
@Id
@GeneratedValue(...)
private long id;
place them on the getters 将它们放在吸气剂上
@Id
@GeneratedValue(...)
public long getId() { ... }
Make sure you make similar changes to all the fields of B
entity. 确保对
B
实体的所有字段进行类似的更改。 Although you can explore @Access(AccessType.PROPERTY/FIELD)
later. 虽然您可以稍后探索
@Access(AccessType.PROPERTY/FIELD)
。
There is already a related bug HHH-3718 regarding this behavior. 有关此行为,已经有一个相关的错误HHH-3718 。
And a related topic on hibernate forum regarding field vs property access type that might be of interest for you Field Vs Property access 而对于现场VS属性访问类型可能是你的兴趣在休眠论坛相关主题的现场Vs的属性访问
Posting your entities classes would help, if this doesn't resolve the issue. 如果不能解决问题,则发布您的实体类将有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.