Kotlin Exposed does not commit transaction

时间:2017-08-05 10:33:25

标签: transactions kotlin kotlin-exposed

Following the example provided on Exposed I am not able to read the created tables/data outside the transaction creating it. I am using h2-in-memory database.

The exception is:

Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "CITIES" not found; SQL statement:

I have added a call to commit but this does not help. If I read the data within the transaction creating the data, as in the example on the link to github, it works fine. Here the a simplified version of it:

fun main(args: Array<String>) {
    Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

    transaction {
        create(Cities)

        City.new {
            name = "St. Petersburg"
        }

        println("Cities: ${City.all().joinToString { it.name }}")
        //I have added this commit here
        commit()
    }
    //I want to read the data outside the transaction, but it does not work
    transaction {
        println("Cities: ${City.all().joinToString { it.name }}")

    }
}

How can I persist the data?

Adding logger.addLogger(StdOutSqlLogger) gives the following output:

SQL: CREATE TABLE IF NOT EXISTS CITIES (ID INT AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(50) NOT NULL)
SQL: INSERT INTO CITIES (NAME) VALUES ('St. Petersburg')
SQL: SELECT CITIES.ID, CITIES.NAME FROM CITIES

3 个答案:

答案 0 :(得分:10)

看起来你离开了内存H2来解决你的问题。请注意,您最初问题的根源可能是因为H2需要被告知要保留JVM的生命周期:

  

JDBC:H2:MEM:测试; DB_CLOSE_DELAY = -1

在此进一步说明:H2 in-memory database. Table not found

答案 1 :(得分:1)

将内存中的数据库更改为Database.connect("jdbc:h2:~/test", driver = "org.h2.Driver")解决了问题。

答案 2 :(得分:1)

确实提交了交易。问题是,当内存数据库关闭时,它被删除,内存数据库在以下情况下被关闭:

  

默认情况下,H2在最后一个连接关闭时关闭数据库

<子> Source

这是一个图表,因此更容易理解一步一步发生的事情(当数据库关闭时,它被完全删除)

diagram

最简单的解决方案是简单地使用实际的文件数据库而不是内存数据库。