为什么编译失败并显示“not found:value Users”?

问题描述:

我想从我的默认数据库postgres检索一行。我已经定义了表格“用户”。为什么编译失败并显示“not found:value Users”?

CONF/application.conf

db.default.driver=org.postgresql.Driver 
db.default.url="jdbc:postgresql://localhost:5234/postgres" 
db.default.user="postgres" 
db.default.password="" 

控制器/ Application.scala

package controllers 

import models.{UsersDatabase, Users} 
import play.api.mvc._ 

object Application extends Controller { 

    def index = Action { 
    Ok(views.html.index(UsersDatabase.getAll)) 
    } 
} 

模型/ Users.scala

package models 

import java.sql.Date 
import play.api.Play.current 
import play.api.db.DB 
import slick.driver.PostgresDriver.simple._ 

case class User(
    id: Int, 
    username: String, 
    password: String, 
    full_name: String, 
    email: String, 
    gender: String, 
    dob: Date, 
    joined_date: Date 
) 

class Users(tag: Tag) extends Table[User](tag, "Users") { 

    def id = column[Int]("id") 
    def username = column[String]("username", O.PrimaryKey) 
    def password = column[String]("password") 
    def full_name = column[String]("full_name") 
    def email = column[String]("email") 
    def gender = column[String]("gender") 
    def dob = column[Date]("dob") 
    def joined_date = column[Date]("joined_date") 
    def * = (id, username, password, full_name, email, gender, dob, joined_date) <> (User.tupled, User.unapply) 
} 

object UsersDatabase { 

    def getAll: List[User] = { 
     Database.forDataSource(DB.getDataSource()) withSession { 
      Query(Users).list 
     } 
    } 
} 

当访问http://localhost:9000/它使编译错误:

[error] .../app/models/Users.scala:36: not found: value Users 
[error]    Query(Users).list 
[error]     ^
[error] one error found 
[error] (compile:compile) Compilation failed 

如何妥善解决这个错误和访问数据?

编译错误消息说明了这一切 - 在范围内没有值Users

更改对象UsersDatabase看起来如下:

object UsersDatabase { 

    val users = TableQuery[Users] 

    def getAll: List[User] = { 
     Database.forDataSource(DB.getDataSource()) withSession { implicit session => 
      users.list 
     } 
    } 
} 

和错误消失,因为你使用本地val users列出数据库中的用户。

一样光滑session val的官方文档中描述Queryinglist的隐含价值(如final def list(implicit session: SessionDef): List[R]),因此implicit session在块:

All methods that execute a query take an implicit Session value. Of course, you can also pass a session explicitly if you prefer:

val l = q.list(session) 
+0

感谢您的大力支持,非常感谢。但运行这给了我更多的错误 '[错误]发现:play.api.mvc.Result [错误] required:slick.driver.PostgresDriver.backend.Session => play.api.mvc.Result [error] (扩展为)slick.driver.PostgresDriver.backend.SessionDef => play.api.mvc.Result [error] Ok(views.html.index(UsersDatabase.getAll)) [error]^ [error] one错误发现 [误差(编译:编译)编译失败 [错误]应用-' index.scala.html '@(用户:列表[用户])

编译' – surenyonjan
+0

它再次感谢。我整理了上面的错误。 – surenyonjan

+0

这是什么?我想将其添加到答案中。 –