Spring Data JPA获取实体外键而不会导致从属实体延迟加载 [英] Spring Data JPA get entity foreign key without causing the dependent entity lazy load

查看:99
本文介绍了Spring Data JPA获取实体外键而不会导致从属实体延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个@Entity A,它使用OneToOne关系船引用了另一个实体B.我使用弹簧数据JpaRepository获取实体A

I have an @Entity A that references another entity B using OneToOne relation ship. I fetch entity A using spring data JpaRepository

A a = aRepository.findById(1);
int b_id = a.getB().getId();

如您所见,我需要查询B表的ID,但是要执行此操作,我需要调用B表的getter,这将导致延迟加载B表本身.我不想这样做,因为我唯一需要的就是获取ID,别无其他,并且该ID存在于第一个A表中.

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. 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?

Is there any trick that will help me to get ID of the dependent table without triggering new query?

更新

@Entity
class A {
    @Id
    private Long id;

    @OneToOne
    private B b;
}

@Entity
class {
    @Id
    private Long id;
}

推荐答案

我怀疑如果不查看实体映射,您的实体类可能正在使用hibernate annotations on the field.这样,如果您甚至在实体上按a.getB().getId()的方式调用getId()方法,都将导致初始化代理(即B对象)并访问数据库以获取它.

Without looking at the entity mapping, I suspect, your entity classes might be using 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 (i.e., B object) and hits the database to fetch it.

因此,如果仅是为了获取实体的id,则可以放置休眠annotations on the getter methods.这不会导致初始化代理(B对象)以返回id的结果.尽管访问id以外的任何属性都将导致命中数据库.

So if the intent is only to get the id of the entity you can place the hibernate annotations on the getter methods instead. This doesn't result initializing the proxy (B object) to return the id. Although accessing any property other than id will result in hitting the database.

HHH-3718

因此,请尝试使用属性/获取器AccessType而不是字段访问.作为示例,而不是将注释放在字段上

So, try using property/getter AccessType instead of field access. As an example instead of placing the annotations on field

@Id
@GeneratedValue(...)
private long id;

将它们放在吸气剂上

@Id
@GeneratedValue(...)
public long getId() { ... }

确保对B实体的所有字段进行类似的更改.虽然您以后可以进行@Access(AccessType.PROPERTY/FIELD)的探索.

Make sure you make similar changes to all the fields of B entity. Although you can explore @Access(AccessType.PROPERTY/FIELD) later.

已经存在与此行为相关的错误HHH-3718 .

There is already a related bug HHH-3718 regarding this behavior.

和休眠论坛上有关您可能感兴趣的字段与属性访问类型的相关主题

And a related topic on hibernate forum regarding field vs property access type that might be of interest for you Field Vs Property access

发布实体类会有所帮助,如果这样做不能解决问题.

Posting your entities classes would help, if this doesn't resolve the issue.

这篇关于Spring Data JPA获取实体外键而不会导致从属实体延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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