Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1. Let's add some data with ambiguous Boolean values (-1, 0, 1, 2)
- INSERT INTO `faculty` (`name`, `isArts`) VALUES
- ('mathematics', 0),
- ('biologic', 1),
- ('physics', 0),
- ('phylology', 2),
- ('historical', -1);
- // 2. Now create a DAO
- import javax.inject.Inject
- import scala.concurrent.Future
- import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
- import play.db.NamedDatabase
- import slick.jdbc.JdbcProfile
- import slick.lifted.ProvenShape
- case class Faculty(facultyId: Option[Long], name: String, isArts: Boolean)
- class FacultyDao @Inject() (
- @NamedDatabase("students") val dbConfigProvider: DatabaseConfigProvider
- ) extends HasDatabaseConfigProvider[JdbcProfile] {
- import profile.api._
- private class FacultyTable(tag: Tag) extends Table[Faculty](tag, "faculty") {
- def facultyId: Rep[Long] = column[Long]("faculty_id", O.PrimaryKey, O.AutoInc)
- def name: Rep[String] = column[String]("name")
- def isArts: Rep[Boolean] = column[Boolean]("isArts")
- override def * : ProvenShape[Faculty] = (facultyId.?, name, isArts) <> (Faculty.tupled, Faculty.unapply)
- }
- private lazy val table = TableQuery[FacultyTable]
- def getAll: Future[Seq[Faculty]] = {
- val query = table.result
- println(query.statements.mkString)
- db.run(query)
- }
- }
- // 3. Now inject this DAO to our controller:
- import javax.inject.Inject
- import scala.concurrent.ExecutionContext
- import play.api.mvc._
- import dao.FacultyDao
- class TestController @Inject()(
- facultyDao: FacultyDao, cc: ControllerComponents)(implicit ec: ExecutionContext) extends AbstractController(cc) {
- // add to routes file: GET /testBoolean controllers.TestController.testBoolean
- def testBoolean: Action[AnyContent] = Action.async {
- facultyDao.getAll map { lst =>
- Ok(s"Result:\n${lst.mkString("\n")}")
- }
- }
- }
- // 4. Call endpoint and see the output:
- // select `faculty_id`, `name`, `isArts` from `faculty`
- //
- // Result:
- // Faculty(Some(1),mathematics,false)
- // Faculty(Some(2),biologic,true)
- // Faculty(Some(3),physics,false)
- // Faculty(Some(4),phylology,true)
- // Faculty(Some(5),historical,true)
- // Summary: Boolean is a C-style: 0 = false, !0 = true
Add Comment
Please, Sign In to add comment