spring-data-relational icon indicating copy to clipboard operation
spring-data-relational copied to clipboard

Support @MappedCollection map key is embedded

Open DreamStar92 opened this issue 8 months ago • 5 comments

This is a relevant feature of composite ID.

The key of the Map type should be the composite id (embedded) when the subentity collection references the aggregate root with the composite id.

DreamStar92 avatar May 14 '25 04:05 DreamStar92

The key of a mapped collection is completely independent from the id of the parent entity.

Do you mean the idColumn? That indeed isn't addressed yet in #1957

schauder avatar May 14 '25 06:05 schauder

That's right, it means that both idColumn and keyColumn need to have this capability.

keyColumn should also be supported in the design. When a child entity of an aggregate root uses a map, the key is always the id of the other aggregate root. If the ID of the aggregate root referenced by the ID is a composite ID, then it means that the key of the map should also be a composite ID (embedded).

DreamStar92 avatar May 14 '25 06:05 DreamStar92

When a child entity of an aggregate root uses a map, the key is always the id of the other aggregate root.

That is wrong. The key is always the key of the Map or the index of the List. It is completely 100% independent of the owning entity or its parents

schauder avatar May 14 '25 08:05 schauder

Maybe it's something wrong with my description or I've abused this feature.

Let me give you a simple example.

This is expected.

    record GoodsId(
            int type, String code
    ) {

    }

    record Goods(
            @Id @Embedded.Nullable GoodsId id,
            String name
    ) {

    }

    record Order(
            @Id long id,
            @MappedCollection(idColumn = "order_id", keyColumn = "type+code") Map<GoodsId, OrderItem> itemMap
    ) {

    }

    record OrderItem(
            @Embedded.Empty GoodsId id,
            int quantity
    ) {

    }

After this, I will try AI translation, hoping to reduce errors in expression.

DreamStar92 avatar May 14 '25 08:05 DreamStar92

Oh, I see. You want to use the id of an entity as the key in a Map.

Interesting, but valid I guess.

schauder avatar May 15 '25 08:05 schauder