【问题标题】:lazy loading for entity in KotlinKotlin 中实体的延迟加载
【发布时间】:2020-06-30 18:45:59
【问题描述】:

我有一些实体AuditEntity。我需要通过entityId 获取eventType 值。

在执行 findFirstByEntityIdOrderByCreatedTimeDesc 方法时,如何使 AuditEntity 中的 dealState 字段始终为零,而不考虑数据库中该字段的值?

如果dealState 字段不是另一个表的键,那么使用@Lazy (import org.springframework.context.annotation.Lazy) 是否正确?

@Entity
@Table(name = "audit")
class AuditEntity(
    @Id
    override var id: Long? = null,

    @Basic
    @Column(name = "entity_id")
    val entityId: Long,

    @Basic
    @Enumerated(EnumType.STRING)
    @Column(name = "event_type")
    val eventType: AuditEventType,

    @Type(type = "jsonb")
    @Column(name = "deal_state", columnDefinition = "jsonb")
    val dealState: Deal? = null
) : BaseEntity<Long>()
@Repository
interface AuditRepository : JpaRepository<AuditEntity, Long> {
    fun findFirstByEntityIdOrderByCreatedTimeDesc(entityId: Long): AuditEntity?
}

【问题讨论】:

    标签: spring kotlin spring-data-jpa spring-data lazy-loading


    【解决方案1】:

    如何使 AuditEntity 中的 dealState 字段在 执行 findFirstByEntityIdOrderByCreatedTimeDesc 方法, 无论数据库中该字段的值如何?

    由于您希望特定字段成为特定查询的特定值,因此您需要自己做。我建议将AuditRepository 包装在另一个将为您完成的课程中。可能的解决方案如下所示:

    @Entity
    @Table(name = "audit")
    data class AuditEntity( // make it a data class
        @Id
        override var id: Long? = null,
    
        @Basic
        @Column(name = "entity_id")
        val entityId: Long,
    
        @Basic
        @Enumerated(EnumType.STRING)
        @Column(name = "event_type")
        val eventType: AuditEventType,
    
        @Type(type = "jsonb")
        @Column(name = "deal_state", columnDefinition = "jsonb")
        val dealState: Deal? = null
    ) : BaseEntity<Long>()
    
    @Repository
    interface AuditRepository : JpaRepository<AuditEntity, Long> {
        fun findFirstByEntityIdOrderByCreatedTimeDesc(entityId: Long): AuditEntity?
    }
    
    @Repository
    class CustomAuditRepository(
        private val auditRepository: AuditRepository
    ) : JpaRepository<AuditEntity, Long> by auditRepository  { // delegate implementation and override only the things you want to be changed
    
        override fun findFirstByEntityIdOrderByCreatedTimeDesc(entityId: Long): AuditEntity? =
            auditRepository.findFirstByEntityIdOrderByCreatedTimeDesc(entityId)?.copy(dealState = ZERO)
    }
    

    【讨论】:

    • 但是首先,无论如何,我得到整个Entity,将deal_state的值放入dealState,然后才将其更改为null?对我来说,在任何阶段都不会在 dealState 中记录 deal_state 对我来说非常重要。
    • @NeverSleeps 我不明白你想要什么。您所说的“在任何阶段都不要在 dealState 中记录 deal_state”是什么意思?
    • 我需要 deal_state 列中包含的 json 不被解析为 Deal 对象。这种解析在某些情况下会出现错误。现在没有办法修复Deal,所以我正在寻找获取eventType但排除阅读deal_state column的方法。
    • 如果我的问题不清楚这一刻,我深表歉意。
    猜你喜欢
    • 2011-03-14
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多