NeverSleeps
NeverSleeps

Reputation: 1912

lazy loading for entity in Kotlin

I have some entity AuditEntity. I need get eventType value by entityId.

How to make the dealState field in AuditEntity always be zero when the findFirstByEntityIdOrderByCreatedTimeDesc method is executed, regardless of the value of this field in the database?

How correct would it be to use @Lazy (import org.springframework.context.annotation.Lazy) if the dealState field is not the key for another table?

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

Upvotes: 0

Views: 599

Answers (1)

Neo
Neo

Reputation: 2039

How to make the dealState field in AuditEntity always be zero when the findFirstByEntityIdOrderByCreatedTimeDesc method is executed, regardless of the value of this field in the database?

Since you want a specific field to be a specific value for a specific query, you need to do it yourself. I would suggest to wrap the AuditRepository in another class which will do it for you. A possible solution could look like this:

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

Upvotes: 1

Related Questions