在Kotlin中实体的延迟加载

时间:2020-06-30 18:45:59

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

我有一个实体AuditEntity。我需要通过eventType获得entityId的值。

无论数据库中该字段的值如何,当执行findFirstByEntityIdOrderByCreatedTimeDesc方法时,如何使AuditEntity中的dealState字段始终为零?

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

@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?
}

1 个答案:

答案 0 :(得分: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)
}