ITADN

Unexpected Eager Loading of Relationships

#2414ClosedHamidreza-mj 创建于 2025-02-19
H
Hamidreza-mjcommented
Hello Friends, When defining one-to-many (Customer -> Address) and many-to-many (Customer <-> Order) relationships using Exposed, related entities are eagerly loaded when calling findById(), even though they should be lazily loaded by default. According to the [Exposed documentation](https://www.jetbrains.com/help/exposed/dao-relationships.html#eager-loading), relations should only be queried when accessed. However, in my case, additional queries for addresses and orders are executed immediately when fetching the parent CustomerEntity, without explicitly accessing these properties. **Tables sample:** ```kotlin object Customers : IntIdTable() { val name = varchar("name", 255) } object Addresses : IntIdTable() { val customer = reference("customer_id", Customers) val location = varchar("location", 255) } object Orders : IntIdTable() { val details = varchar("details", 255) } object CustomerOrders : Table() { val customer = reference("customer_id", Customers) val order = reference("order_id", Orders) override val primaryKey = PrimaryKey(customer, order) } ``` **Entities:** ```kotlin class CustomerEntity(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<CustomerEntity>(Customers) var name by Customers.name // One-to-Many: A customer can have multiple addresses val addresses by AddressEntity referrersOn Addresses.customer // Many-to-Many: A customer can have multiple orders var orders by OrderEntity via CustomerOrders } class AddressEntity(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<AddressEntity>(Addresses) var customer by CustomerEntity referencedOn Addresses.customer var location by Addresses.location } class OrderEntity(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<OrderEntity>(Orders) var details by Orders.details } ``` I only want to fetch a CustomerEntity without accessing addresses or orders: ```kotlin // Expected: Only fetch customer without relations // like simple select: `select * from customer where id = 1;` val customer = CustomerEntity.findById(1) ``` but in sql log result in console I see something like this: > SELECT customers.id, customers.name FROM customers WHERE customers.id = ? > SELECT addresses.id, addresses.location, addresses.customer_id FROM addresses WHERE addresses.customer_id = ? > SELECT orders.id, orders.details, customer_orders.customer_id, customer_orders.order_id > FROM orders > INNER JOIN customer_orders ON customer_orders.order_id = orders.id > WHERE customer_orders.customer_id = ? that means join has occurred and extra relations are be loaded! for best performance and reduce querying i don't need to load this extra relations, i need to load it manually with exposed DAO functions like: CustomerEntity.load(CustomerEntity::addresses, CustomerEntity::orders)
关闭于 2025-02-19 1 条评论