創(chuàng)建Play項目后配置sbt冯袍,導(dǎo)入reactiveMongodb:
name := """play-scala"""
version := "1.0-SNAPSHOT"
scalaVersion := "2.11.8"
libraryDependencies += jdbc
libraryDependencies += cache
libraryDependencies += ws
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test
val reactiveMongoVer = "0.12.3"
libraryDependencies ++= Seq(
// "org.reactivemongo" %% "reactivemongo" % "0.12"
"org.reactivemongo" %% "play2-reactivemongo" % reactiveMongoVer
)
routesGenerator := InjectedRoutesGenerator
fork in run := true
lazy val root = (project in file(".")).enablePlugins(PlayScala)
在application.conf文件中配置Module和Mongodb的地址:
play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"
mongo-async-driver {
akka {
loglevel = WARNING
}
}
mongodb.uri = "mongodb://localhost:27017/mydb"
創(chuàng)建數(shù)據(jù)實體:
ackage entity
/**
* 用戶實體對象
* @param id
* @param name
* @param password
* @param email
* @param createDate
* @param modifyDate
*/
case class User(val id:String ,
val name: String,
val password:String,
val email:String,
val createDate:Long,
val modifyDate:Long)
object User{
import play.api.libs.json._
implicit object UserWriter extends OWrites[User]{
override def writes(o: User): JsObject = {
Json.obj(
"_id"->o.id,
"name"->o.name,
"password"->o.password,
"email"->o.email,
"createDate"->o.createDate,
"modifyDate"->o.modifyDate
)
}
}
implicit object UserReader extends Reads[User]{
override def reads(json: JsValue): JsResult[User] = {
json match {
case js:JsObject=>try{
val id = (json \ "_id").as[String]
val name = (json \ "name").as[String]
val password = (json \"password").as[String]
val email = (json \"email").as[String]
val createDate = (json \ "createDate").as[Long]
val modifyDate = (json \ "modifyDate").as[Long]
JsSuccess(User(id,name,password,email,createDate,modifyDate))
}catch {
case cause:Throwable=>JsError(cause.getMessage)
}
case _ => JsError("error")
}
}
}
}
mongodb的增刪改查:
package controllers
import java.util.UUID
import javax.inject.{Inject, Singleton}
import entity.User
import play.api._
import play.api.mvc._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import reactivemongo.api.QueryOpts
import reactivemongo.bson.BSONDocument
import reactivemongo.play.json._
import reactivemongo.play.json.collection._
/**
* Created by zhuleqi on 2017/3/22.
*/
class UserController @Inject() (val reactiveMongoApi: ReactiveMongoApi) extends Controller with MongoController with ReactiveMongoComponents {
/**
* 獲取mongoDb的collection
* @return
*/
def userCollection = reactiveMongoApi.database.
map(_.collection[JSONCollection]("user"))
def regist()=Action{
Ok(views.html.userRegist("用戶注冊"))
}
/**
*插入用戶
* @param name
* @param passowrd
* @param email
* @return
*/
def insert(name:String,passowrd:String,email:String)=Action.async{
var user = User(UUID.randomUUID().toString,
name,
passowrd,
email,
System.currentTimeMillis(),
System.currentTimeMillis()
)
userCollection.flatMap(_.insert(user)).map(wr =>Ok(user.toString))
}
/**
* 更新User的Email
* @param id
* @param email
* @return
*/
def update(id:String,email:String) = Action.async{
userCollection.flatMap(_.update(Json.obj("_id"->id),Json.obj("$set"->Json.obj("email"->email)))).map(ss=>{
Ok("ok")
})
}
/**
*根據(jù)ID查找用戶
* @param id
* @return
*/
def find(id:String)=Action.async{
userCollection.flatMap(_.find(Json.obj("_id"->id)).cursor[User]().collect[List]()).map(users=>{
Ok(users.head.toString);
})
}
/**
* 刪除用戶
* @param id
* @return
*/
def remove(id:String) =Action.async{
userCollection.flatMap(_.remove(Json.obj("_id"->id))).map(findMS =>{
Ok("delete ok")
})
}
/**
* 分頁查找用戶列表
* @param page
* @param pageSize
* @return
*/
def findAll(page:Int,pageSize:Int) = Action.async{
val startIndex = pageSize*(page-1);
val endIndex = pageSize*page
userCollection.flatMap(_.find(Json.obj()).options(QueryOpts(skipN =startIndex ,batchSizeN = pageSize)).cursor[User]().collect[List](pageSize)).map(users=>{
var userStr = ""
for (user <- users){
userStr+=user.toString
}
Ok(userStr)
})
}
def login(name:String,password:String) = Action{
Ok("")
}
}
rout文件的相應(yīng)配置:
POST /user/insert controllers.UserController.insert(name:String?="",password:String?="",email:String?="")
GET /user/find/:id controllers.UserController.find(id:String)
GET /user/findAll/:page/:pageSize controllers.UserController.findAll(page:Int,pageSize:Int)
GET /user/update controllers.UserController.update(id:String ?="",email:String ?="")
GET /user/remove/:id controllers.UserController.remove(id:String)
GET /user/regist controllers.UserController.regist()