0

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?

1 Answers1

0

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

Osher Shuman
  • 213
  • 3
  • 7