简体   繁体   English

Fetch Lazy对于具有复合PK的ManyToOne不起作用

[英]Fetch Lazy does not work for ManyToOne with composite PK

I have the following database structure 我有以下数据库结构

CREATE TABLE a (
    id TEXT PRIMARY KEY,
    creation_date TIMESTAMP WITH TIME ZONE NOT NULL
);

CREATE TABLE b (
    id text
    a_id TEXT REFERENCES a,
    active BOOLEAN NOT NULL,
    creation_date TIMESTAMP WITH TIME ZONE NOT NULL,
    modification_date TIMESTAMP WITH TIME ZONE NOT NULL,
    version INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (id, a_id)
);

CREATE UNIQUE INDEX ON b (a_id) WHERE (active);
CREATE UNIQUE INDEX ON b (id) WHERE (active);

And JPA entities, where B has composite PK and FK for A 和JPA实体,其中B具有复合PK和FK用于A.

@Entity
@Table (name = "a")
class A (

    @Id
    var id: String
)

@Entity
@Table (name = "b")
class B (

    @EmbeddedId
    @AttributeOverride (name = "aId", column = Column (name = "a_id", updatable = false))
    var pk: Pk,

    var active: Boolean

) {

    @JoinColumn (name = "a_id")
    @MapsId ("aId")
    @ManyToOne (cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
    var a: A? = null

    @Embeddable
    class Pk (

        var id: String,

        var aId: String?
    ): Serializable {

        override fun equals (other: Any?): Boolean {
            ...
        }

        override fun hashCode (): int {
            ...
        }
    }
}

Repository 知识库

interface BRepository: JpaRepository <B, B.Pk>

When i call 我打电话的时候

bRepository.findById (B.Pk ("b_id", "a_id"))

then two requests appear in the hibernate log 然后在hibernate日志中出现两个请求

Hibernate: select b0_.a_id as a_id1_1_0_, b0_.id as id2_1_0_, b0_.active as active3_1_0_, b0_.creation_date as creation4_1_0_, b0_.modification_date as modifica5_1_0, your own; and b0_.id =?
Hibernate: select a0_.id as id1_0_0_, a0_.creation_date as creation2_0_0_ from a a__ where a0_.id =?

FetchType.LAZY in B entity does not work and A is loaded. B实体中的FetchType.LAZY不起作用且加载了A.

How to fix mapping for A lazy load? 如何修复延迟加载的映射?

The point of lazy loading is that when you fetch A, it will not fetch the one to many mapping so B will not be fetched. 延迟加载的重点是,当你获取A时,它不会获取一对多的映射,因此不会获取B. You can USE FetchType.EAGER to resolve this. 您可以使用FetchType.EAGER来解决此问题。 Too understand more on the difference between LAZY and EAGER Fetch types, please look at this answer 太了解LAZY和EAGER Fetch类型之间的区别,请看这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM