首页 > 解决方案 > Kotlin DTO 实体映射递归问题

问题描述

所以我试图将 Dto 映射到实体,反之亦然,但由于我在它们之间有双向连接,我遇到了递归错误,是否有一个简单的解决方法,我刚开始使用 kotlin,还没有找到任何解决方案。

这些是我的扩展类。

注册规则扩展.kt

fun RegistrationRuleEntity.toDto() = RegistrationRuleDto(
    id = id,
    count = count,
    description = description,
    tier = tier,
    licenses = licenses?.map { license -> license.toDto()}
)

fun RegistrationRuleDto.toEntity() = RegistrationRuleEntity(
        id = id,
        count = count,
        description = description,
        tier = tier,
        licenses = licenses?.map { license -> license.toEntity()}
)

许可证扩展.kt

fun LicenseEntity.toDto() = LicenseDto(
        id = id,
        name = name,
        licenseId = licenseId,
        rules = rules?.map { rule -> rule.toDto() },
        version = version
)

fun LicenseDto.toEntity() = LicenseEntity(
        id = id,
        name = name,
        licenseId = licenseId,
        rules = rules?.map { rule -> rule.toEntity() },
        version = version
)

如果我理解正确,问题是我的许可证在我的规则上调用 .toDto ,然后该规则想要在我的许可证上调用 .toDto 并且它进入无限循环。

感谢您提前回答!

标签: springkotlin

解决方案


所以我从朋友和同事那里得到了一些想法。

我的第一个想法:

由于许可证知道它有哪些规则,因此我没有理由根据规则获得许可证,因此我可以将其设置为空。

第二个想法:

我只将规则的 ID 存储在许可证上,如果我需要规则,我会通过他们的 ID 请求它们。

如果您有任何其他想法,请随时发表评论。:D


推荐阅读