There is such a 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); INSERT INTO a (id, creation_date) VALUES ('a_id', now()); INSERT INTO b (id, a_id, active, creation_date, modification_date) VALUES ('b_id', 'a_id', TRUE, now(), now());
JPA mapping
@Entity @Table(name = "a") @EntityListeners(AuditingEntityListener::class) class A( @Id var id: String ) { @CreatedDate @Column(name = "creation_date", updatable = false) lateinit var creationDate: OffsetDateTime } @Entity @Table(name = "b") @EntityListeners(AuditingEntityListener::class) 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 @CreatedDate @Column(name = "creation_date", updatable = false) lateinit var creationDate: OffsetDateTime @LastModifiedDate @Column(name = "modification_date") lateinit var modificationDate: OffsetDateTime @Version var version: Int = 0 @Embeddable class Pk( var id: String, var aId: String? ): Serializable { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Pk if (id != other.id) return false if (aId != other.aId) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + (aId?.hashCode() ?: 0) return result } companion object { private const val serialVersionUID: Long = 1L } } }
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 logs
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_, b0_.version as version6_1_0_ from b b0_ where b0_.a_id=? and b0_.id=? Hibernate: select a0_.id as id1_0_0_, a0_.creation_date as creation2_0_0_ from a a0_ where a0_.id=?
FetchType.LAZY is obtained, in effect B does not work, and A is loaded.
How to fix mapping so that A doesn't load?