mvysny / vok-orm

Mapping rows from a SQL database to POJOs in its simplest form
MIT License
21 stars 4 forks source link

Table.findById does not use @As metadata #7

Closed DALDEI closed 5 years ago

DALDEI commented 5 years ago

Related slightly to #5 -- given a table (my case postgress) with a key id column not named "id" (say "myid") and a class like :

data class mytable (
 @As("myid")
  override var id : Int? = 0,
  var name : String? = null
) : Entity<Int> {
  companion object : Dao<mytable> {} 
}

some operations like findAll work fine but findById does not.

...

val item = mytable.findById(123)  --> 

org.sql2o.Sql2oException: Database error: ERROR: column "id" does not exist
  Position: 29
        at org.sql2o.Query$ResultSetIterableBase.<init>(Query.java:332) ~[sql2o-1.5.4.jar:?]
        at org.sql2o.Query$10.<init>(Query.java:412) ~[sql2o-1.5.4.jar:?]
        at org.sql2o.Query.executeAndFetchLazy(Query.java:412) ~[sql2o-1.5.4.jar:?]
        at org.sql2o.Query.executeAndFetchFirst(Query.java:480) ~[sql2o-1.5.4.jar:?]
        at org.sql2o.Query.executeAndFetchFirst(Query.java:469) ~[sql2o-1.5.4.jar:?]
        at com.github.vokorm.ConnectionUtilsKt.findById(ConnectionUtils.kt:24) ~[vok-orm-0.15.jar:?]

I belive this is due to an oversight in findById()

fun <T : Any> Connection.findById(clazz: Class<T>, id: Any): T? =
    createQuery("select * from ${clazz.entityMeta.databaseTableName} where id = :id")
        .addParameter("id", id)
        .setColumnMappings(clazz.entityMeta.getSql2oColumnMappings())
        .executeAndFetchFirst(clazz)

where similar functions use the metadata

fun <T: Any> Connection.deleteById(clazz: Class<T>, id: Any) {
    createQuery("delete from ${clazz.entityMeta.databaseTableName} where ${clazz.entityMeta.idProperty.dbColumnName}=:id")
        .addParameter("id", id)
        .executeUpdate()
}

should not findById use :

${clazz.entityMeta.idProperty.dbColumnName}=:id"

mvysny commented 5 years ago

Thank you for letting me know! Let me add proper tests for such an entity.

mvysny commented 5 years ago

Released in vok-orm 0.16

DALDEI commented 5 years ago

Awesome ! I sat down today to work more on the project and hit this again thought "maybe its fixed now" -- click click v(n+1) yes ! Thanks !