mvysny / vok-orm

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

@As aanotation not work in custom query #9

Closed zalevan closed 7 months ago

zalevan commented 5 years ago

@As aanotation not work in custom query. For simple try add @As to id property like "test_id", and then fetch to entity class by "select * ...".

mvysny commented 5 years ago

Hi, thanks for letting me know! Sounds like #7 but may be something else. Can you please share a small reproducible code example?

zalevan commented 5 years ago

Yes, it is like #7. Reflection in sql2o dont use @as anntotation for fetch class. This is reason.

My test code:

create table TestClass (
  test_id serial primary key,
  testname varchar(200) not null
);
data class TestClass(
        @As("test_id") override var id: Int? = null,
        var testname: String? = null
) : Entity<Int> {
    companion object : Dao<TestClass>{
        fun selectAllTest(): List<TestClass> = db {
            con.createQuery("SELECT * FROM testclass")
                    .executeAndFetch(TestClass::class.java)
        }
    }
}

val result = TestClass.selectAllTest()

Then i modifed:

data class TestClass(
        @As("test_id") override var id: Int? = null,
        var testname: String? = null
) : Entity<Int> {
    var test_id
        get() =  id
        set(value) { id = value }

    companion object : Dao<TestClass>{
        fun selectAllTest(): List<TestClass> = db {
            con.createQuery("SELECT * FROM testclass")
                    .executeAndFetch(TestClass::class.java)
        }
    }
}

an error is gone.

mvysny commented 5 years ago

Ah, that is correct. You need to call setColumnMappings(TestClass::class.entityMeta.getSql2oColumnMappings()) on Sql2o's Query so that @As is taken into effect also by Sql2o:

        fun selectAllTest(): List<TestClass> = db {
            con.createQuery("SELECT * FROM testclass")
                    .setColumnMappings(TestClass::class.entityMeta.getSql2oColumnMappings())
                    .executeAndFetch(TestClass::class.java)
        }

I wonder if there is a way for vok-orm to pre-configure Sql2o so that the @As annotations are taken into effect even without the need to call the setColumnMappings() function...

Tip: since your companion object implements Dao, you can simply call TestClass.findAll().

This definitely needs to be mentioned in the documentation and in the @As kdoc as a minimum.

mvysny commented 7 months ago

Closed since we're using JDBI instead of Sql2o now.