You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Kotlin Exposed ORM创建User表时遇'Unresolved reference: new'错误求助

解决Kotlin Exposed ORM中"Unresolved reference: new"错误

你遇到的这个错误核心原因很明确:一方面Kotlin本身不需要new关键字来创建对象(这是Java的语法),另一方面Exposed的DAO实体类也不能直接通过构造函数实例化,必须用框架提供的方式创建。我来帮你梳理正确的写法和排查要点:

1. 修正实体类定义(优化包引用)

你的实体类结构没问题,只是可以调整伴生对象的泛型引用,避免全路径带来的潜在问题:

package test5Gr.test5Artif

import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable

// 定义User数据表结构
object Users : IntIdTable() {
    val name = varchar("name", 50).index()
    val age = integer("age")
}

// 定义对应的实体类
class User(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<User>(Users) // 直接引用当前类即可,无需全路径
    var name by Users.name
    var age by Users.age
}

2. 主函数的正确写法(去掉new,用Exposed规范方式创建实体)

Exposed的IntEntity必须通过伴生对象的new方法来创建实例,同时所有数据库操作要包裹在transaction块中。这里给你一个完整的可运行示例:

import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction

fun main() {
    // 初始化数据库连接(以H2内存库为例,你可以替换成自己的数据库)
    Database.connect("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver")

    transaction {
        // 先创建数据表
        SchemaUtils.create(Users)

        // 正确创建User实体:用伴生对象的new方法,传入初始化块
        val newUser = User.new {
            name = "Mohammad"
            age = 30
        }

        // 验证结果
        println("创建成功:用户${newUser.name},年龄${newUser.age},ID${newUser.id.value}")
    }
}

额外需要检查的点

  • 确保项目已正确引入Exposed依赖,比如Gradle配置:
    implementation("org.jetbrains.exposed:exposed-core:0.44.1")
    implementation("org.jetbrains.exposed:exposed-dao:0.44.1")
    implementation("org.jetbrains.exposed:exposed-jdbc:0.44.1")
    // 对应数据库驱动,比如H2
    implementation("com.h2database:h2:2.2.224")
    
  • 不要尝试用new User(...)这种Java风格的写法,Kotlin不支持,且Exposed的实体也不允许直接调用构造函数。

按照上面的方式调整后,你的Unresolved reference: new错误应该就能解决了。

内容的提问来源于stack exchange,提问作者Mohammad Daliri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:58:29