使用复合PK的Fetch Lazy不适用于ManyToOne

时间:2019-03-29 10:44:56

标签: hibernate jpa

我具有以下数据库结构

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);

和JPA实体,其中B具有A的组合PK和FK

@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 {
            ...
        }
    }
}

存储库

interface BRepository: JpaRepository <B, B.Pk>

当我打电话

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

然后两个请求出现在休眠日志中

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

B实体中的FetchType.LAZY无法正常工作,并且已加载A。

如何修复延迟加载的映射?

1 个答案:

答案 0 :(得分:0)

延迟加载的要点是,当您获取A时,它不会获取一对多映射,因此不会获取B。您可以使用FetchType.EAGER来解决此问题。太了解LAZY和EAGER提取类型之间的区别,请查看此answer