Norm is an utility built on top of Anorm to be used in playframework scala projects. It's not a complete ORM with a lot of complex things.
- Because repeating yourself is boring. For simple cases, when you create 2 or 3 classes(models?) to access the database, you'll end up writting a lot of the same things.
- Because to learn even a new idiomatic way to write the same old sql is not a great innovation
- If you're writting a very complex model (joins, inheritance,...) - for now - No
- If you're not comfortable with unchecked type - No
- If you want transaction between models - for now - No
- If you have a lot of models with simple access pattern and don't want to learn a new way to access SQL dbs - yes
- Add Norm to your project:
This project was forked from Ricardo Lazaro's norm but it diverged too much and is not published yet, so just copy the file Norm.scala to your project.
- Create a model class extending Norm:
import models.frameworks.{NormCompanion, Norm}
import play.api.libs.json.{JsObject, JsValue, Json}
case class Product(
name: String,
otherEntityId: Long,
monetaryValue: BigDecimal,
config: JsValue,
enabled: Boolean = true,
priority: Int = 0,
id: Pk[Long] = NotAssigned
) extends Norm[Product] {
object Product extends NormCompanion[Product]{
implicit val ProductFormat = Json.format[Product]
def findByOtherEntity(otherEntity: OtherEntity): List[Product] = findByOtherEntity(otherEntity.id.get)
def findByOtherEntity(otherEntityId: Long): List[Product] = findByProperties(Map("otherEntityId" -> otherEntityId, "enabled" -> true))
}
- Inserting a product:
val product = Product(someName, otherEntityId, someMonetaryValue, someJson).save
Or
```scala
val optionId = Product.create(
Map(
"name" -> "productName",
"otherEntityId" -> 1l,
"monetaryValue" -> new BigDecimal("10.00"),
"config" -> JsNull
)
)
```
-
Updating a product
product.name = newProductName product.otherEntityId = otherProductId product.update
-
Partial update
product.update( Map( "name" -> newProductName, "otherEntityId" -> otherProductId ) )
-
Find a product
val product = Product.find(2l) // by id 2l
val productOption = Product.findOption(2l) // by id 2l
val products = Product.findByProperty("name", someName)
val products = Product.findByProperties(Map("name" -> someName, "enabled" -> true))