我有一段时间在我的ScalaTest测试用例中使用测试数据库,如documentation examples所示。
我有一个默认数据库和一个testdb数据库,我的规范看起来像
class JobSpec extends FlatSpec with AutoRollback {
DBsWithEnv("test").setup('testdb)
override def db = NamedDB('testdb).toDB
override def fixture(implicit session:DBSession) = {
User.insert("test_user")
}
it should "create a new user" in { implicit session: DBSession =>
User.sqlFind("test_user") //succeeds
User.dslFind("test_user") //fails
}
}
似乎我的查询使用sql工作,但使用dsl的查询没有。 DSL查询错误,尝试访问默认数据库,但sql查询正确使用' testdb数据库。这是错误
Connection pool is not yet initialized.(name:'default)
java.lang.IllegalStateException: Connection pool is not yet initialized.(name:'default)
这是“用户类”
case class User(name: String)
object User extends SQLSyntaxSupport[User] {
def apply(u: SyntaxProvider[User])(rs: WrappedResultSet) = apply(u.resultName)(rs)
def apply(j: ResultName[User])(rs: WrappedResultSet) = new User(rs.get(u.name))
override val tableName = "users"
val u = User.syntax("u")
def dslFind(name: String)(implicit session: DBSession) =
withSQL {
select.from(User as u).where.eq(u.name, name)
}.map(User(u)).single().apply()
def sqlFind(name: String)(implicit session: DBSession) =
sql""" select (name) from users where name = $name;"""
.map(rs => new User(rs.string(1)).single().apply()
}
在调用DSL创建的查询时,任何人都知道为什么要尝试使用默认数据库而不是testdb?谢谢!
答案 0 :(得分:4)
您需要覆盖SQLSyntaxSupport,如下所示:
override val connectionPoolName = 'testdb
原因是SQLSyntaxSupport在第一次访问时从JDBC元数据中提取列。
http://scalikejdbc.org/documentation/sql-interpolation.html
如果您希望避免自动访问元数据,请覆盖列或使用autoColumns宏。