Created
July 16, 2013 01:36
-
-
Save agnaldo4j/6005095 to your computer and use it in GitHub Desktop.
Exemplo simples de GRUD com Scala, Salat, Casbah e MongoDB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.codesimples.persistence.target | |
import scala.collection.JavaConversions._ | |
import com.codesimples.model.target.User | |
import com.novus.salat._ | |
import com.novus.salat.global._ | |
import com.mongodb.casbah.Imports._ | |
import java.util.UUID | |
class UserPersistence(connection:MongoConnection) { | |
val db = connection("suabase") | |
db.authenticate("reality1", "senhadb") | |
val collection = db("users") | |
def buildNew(_id:String = UUID.randomUUID().toString): User = User(_id) | |
def save(user:User) = collection += grater[User].asDBObject( user ) | |
def update(user:User) = { | |
val q = MongoDBObject("_id" -> user._id) | |
collection.update(q, MongoDBObject("$set" -> MongoDBObject( | |
"name" -> user.name, | |
"email" -> user.email, | |
"password" -> user.password | |
) | |
) | |
) | |
} | |
def delete(user:User) = collection -= grater[User].asDBObject( user ) | |
def findAll(): Option[List[User]] = { | |
val cursor = collection.find() | |
val results = (for { x <- cursor} yield grater[User].asObject( x ) ) | |
Some[List[User]]( results.toList ) | |
} | |
def findById(id:String): Option[User] = { | |
val cursor = collection.findOne(MongoDBObject("_id" -> id)) | |
cursor.map { user => Some[User]( grater[User].asObject( user ) ) }.getOrElse { None } | |
} | |
def findByEmailAndPassword(email:String, password:String): Option[User] = { | |
val cursor = collection.findOne(MongoDBObject("email" -> email, "password" -> password)) | |
cursor.map { user => Some[User]( grater[User].asObject( user ) ) }.getOrElse { None } | |
} | |
def clean() = collection.remove(MongoDBObject.empty) | |
def close() = connection.close() | |
} | |
object UserPersistence { | |
def buildNew: UserPersistence = { | |
new UserPersistence( MongoConnection("localhost" , 27017) ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment