How could I simplify my code by using interfaces (...
# komapper
a
How could I simplify my code by using interfaces (or maybe sealed interfaces if needed) ? I have a bunch of data classes that also are komapper tables, and I want to generate a few shortcut methods on each class, so I can just do
User(username = "", password = "").insert()
I don't know if it's a good thing to do, stop me if I'm wrong ! But I can't find any way to get the
QueryDSL.insert()
method work, it always says that I'm having the wrong type, even when getting the metamodel by reflection or by a property in my interface, I don't quite get it Could you help me figuring all this ?
t
Try following code:
Copy code
val db = JdbcDatabase("jdbc:h2:mem:example;DB_CLOSE_DELAY=-1")

interface Common<ENTITY : Any, ID : Any, META : EntityMetamodel<ENTITY, ID, META>> {
    val metamodel: META
    fun insert(entity: ENTITY): ENTITY {
        return db.runQuery(QueryDsl.insert(metamodel).single(entity))
    }
}

@KomapperEntity
data class User(@KomapperId val id:Int) {
    companion object: Common<User, Int, _User> {
        override val metamodel = Meta.user
    }
}

@KomapperEntity
data class Game(@KomapperId val id:Int) {
    companion object: Common<Game, Int, _Game> {
        override val metamodel = Meta.game
    }
}
You can insert your entities as follows:
Copy code
val newUser = User.insert(User(id = 1))
val newGame = Game.insert(Game(id = 1))
a
Thanks ! I'll try this tomorrow when I will start working, but it's pretty complex and I'm working with 2 people new to Kotlin, I'm trying to let them learn the language with a smooth learning curve Maybe as your code is pretty hard to understand for a beginner, we sadly won't use it, I'm unsure :'(
t
A more common method is to use repository patterns. It may fit your case.
Copy code
abstract class Repository<ENTITY : Any, ID : Any, META : EntityMetamodel<ENTITY, ID, META>>(protected val db: JdbcDatabase) {
    abstract val metamodel: META
    fun insert(entity: ENTITY): ENTITY {
        return db.runQuery(QueryDsl.insert(metamodel).single(entity))
    }
}

class UserRepository(db: JdbcDatabase) :Repository<User, Int, _User>(db) {
    override val metamodel = Meta.user
}

class GameRepository(db: JdbcDatabase) :Repository<Game, Int, _Game>(db) {
    override val metamodel = Meta.game
}
a
Oh thanks, I'll share this with my team and we'll discuss !