Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自动填充公共字段 #582

Open
136093330 opened this issue Sep 19, 2024 · 1 comment
Open

自动填充公共字段 #582

136093330 opened this issue Sep 19, 2024 · 1 comment

Comments

@136093330
Copy link

不管是使用ksp方式,还是BaseTable,在进行操作的时候,如何自动填充公共字段,比如createTime . updateTime, 这类的公共字段,而不用每次操作都需要手动去写一遍,框架是否有拦截器 或者 注解之类的方式?

@iFleey
Copy link

iFleey commented Nov 14, 2024

Agree.
I'm using Ktorm in my Spring Boot project where all my entity classes have createAt and updateAt fields.
I added the relevant autofill to BaseDao and I'll share my approach:
I defined an interface that represents the time, like

interface BaseDateTimeColumn {
  var createAt: LocalDateTime?
  var updateAt: LocalDateTime?
}

then, Implement it in my User class,

@Table("user")
interface User : Entity<User>, BaseDateTimeColumn {
  @PrimaryKey
  val id: Int
  var username: String
  var password: String
  var nickname: String
  var enabled: Boolean
  override var createAt: LocalDateTime?
  override var updateAt: LocalDateTime?
}

Now, modify the add and update functions of BaseDao,

abstract class BaseDao<E : Entity<E>, T : Table<E>>(private val tableObject: T) {
  @Autowired
  protected lateinit var database: Database

  /**
   * Insert the given entity into the table and return the effected record number.
   */
  open fun add(entity: E): Int {
    if (entity is BaseDateTimeColumn) {
      val now = LocalDateTime.now()
      entity.createAt = now
      entity.updateAt = now
    }
    return database.sequenceOf(tableObject).add(entity)
  }

  /**
   * Update properties of the given entity to the table and return the effected record number.
   */
  open fun update(entity: E): Int {
    if (entity is BaseDateTimeColumn) {
      entity.updateAt = LocalDateTime.now()
    }
    return database.sequenceOf(tableObject).update(entity)
  }
  // ...
}

Okey, now your calls to add and update will automatically populate the updates.
I hope that helps. I can't think of a better way, just sharing my humble opinion lol, if you have a better way, please share it with me, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants