简体   繁体   中英

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

@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: 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.

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. You can USE FetchType.EAGER to resolve this. Too understand more on the difference between LAZY and EAGER Fetch types, please look at this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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