使用Hibernate批注的惰性一对一可选双向映射

使用Hibernate批注的惰性一对一可选双向映射

本文介绍了使用Hibernate批注的惰性一对一可选双向映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Hibernate批注创建一个懒惰的一对一双向可选"映射.我知道 @MappedBy @JoinColumn 的正常用法会导致每次触发N + 1个查询.

I want to create a Lazy One-to-one Bidirectional 'Optional' Mapping using Hibernate annotations. I know that the normal usage of @MappedBy and @JoinColumn result in N+1 queries being fired every time.

有没有办法可以避免这种情况?不仅在运行时,而且在 POJO 级别.我正在使用 Hibernate 4.3 ,因此无法考虑字节码增强.

Is there a way I can avoid this? Not just at runtime, but at the POJO level. I am using Hibernate 4.3, so can't think about bytecode enhancement.

如果没有出路,可以在单向映射中应用标准.例如,我有 A<->B, C->A 作为映射.我正在搜索 B .当 C A 显然是单向的时,是否可以对 C 施加限制?

Further, if there is no way out, is it possible to apply criteria on unidirectional mappings. For example, I have A <-> B, and C -> A as mappings. And I am searching on B. Is it possible to apply a restriction on C when C is clearly unidirectional with A?

推荐答案

我找不到 LAZY双向@OneToOne 的完整但最少的示例,所以就在这里.它既不依赖于休眠版本,也不滥用 @OneToMany .

I could not find a complete but minimal examples of LAZY bidirectional @OneToOne, so here it is. It is neither hibernate-version-dependent nor does it misuse @OneToMany.

父母

定义 id 并负责管理一致性/同步,但是从技术上讲,它不拥有这种关系,因为它不能引用 B 中的任何唯一索引(或至少我们不想添加冗余数据.

Defines the id and is responsible for managing the consistency/synchronization, but technically does not own the relationship, because it can not reference any unique index in B (or at least we do not want to add redundant data).

@Entity
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(
            mappedBy = "a",
            cascade = CascadeType.ALL,
            orphanRemoval = true,
            fetch = FetchType.LAZY
    )
    private B b;

    public void setB(B b) {
        if (b == null) {
            if (this.b != null) {
                this.b.setA(null);
            }
        } else {
            b.setA(this);
        }
        this.b = b;
    }
    // ... other setters/getters
}

孩子

通过重新使用父代 A 的ID,从技术上拥有这种关系.

Technically owns the relationship by re-using the id of parent A.

@Entity
public class B {
    @Id
    // Not generated but shared with A
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id") // otherwise use "a_id" instead of "id" in the DB column
    private A a;
    // ... other setters/getters
}

这是表格的外观(假设postgres):

And this is how the tables should look like (assuming postgres):

CREATE TABLE a (
    id bigint NOT NULL PRIMARY KEY,
);

CREATE TABLE b (
    id bigint NOT NULL PRIMARY KEY,
    FOREIGN KEY (id) REFERENCES a(id);
);

这篇关于使用Hibernate批注的惰性一对一可选双向映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:26