play framework anorm orm 化构想

play 框架引入了一个简单的数据库访问层:anorm。

使用anorm做模型层,代码大致如下:

Scala代码  

  1. case class Dog(id: Pk[Long], name: String, age: String)  
  2.   
  3. object Dog {  
  4.   val simple = get[Pk[Long]]("dog.id") ~ str("name") ~ int("age") map {  
  5.     case id ~ name ~ age => Dog(id, name, age)  
  6.   }  
  7.   
  8.   def findById(id: Long) = DB.withConnection {  
  9.     implicit connection =>  
  10.       SQL("select * from dog where id = {id}").on('id -> id).as(Dog.simple.singleOpt)  
  11.   }  
  12.   
  13.   def create(dog: Dog) = DB.withConnection {  
  14.     implicit connection =>  
  15.       val idOpt: Option[Long] = SQL(  
  16.         """  
  17.           insert into dog (name, age)  
  18.           values ({name}, {age})  
  19.         """  
  20.       ).on(  
  21.         'name -> dog.name,  
  22.         'age -> dog.age  
  23.       ).executeInsert()  
  24.       val result = dog.copy(id = Id(idOpt.get))  
  25.       result  
  26.   }  
  27.   
  28.   def update(id: Long, dog: Dog) = DB.withConnection {  
  29.     implicit connection =>  
  30.       SQL(  
  31.         """  
  32.         update dog set name = {name}, age = {age} where id = {id}  
  33.         """  
  34.       ).on(  
  35.         'id -> id,  
  36.         'name -> dog.name,  
  37.         'age -> dog.age  
  38.       ).executeUpdate()  
  39.   }  
  40.   
  41. }  

 

    明显比JPA繁杂,那么,有没有办法封装下anorm,使它更象orm,提供更好的维护性,更快的开发速度?

    在scala 2.10中,引入的试验性功能:macro, reflection,或许就是问题的答案(现在只是一个构想,会抽空实现验证下),还是代码为先:

Scala代码  

  1. trait Modal[T] {  
  2.   val simple = macro ModalMacroImpl.simple[T]  
  3.   def findById(id: Long): Option[T] = macro ModalMacroImpl.find  
  4.   def create(o: T) = macro ModalMacroImpl.create  
  5.   def update(id: Long, o: T) = macro ModalMacroImpl.update  
  6.   def list = macro ModalMacroImpl.list  
  7. }  
  8.   
  9. object Dog extends Modal[Dog] {  
  10.   def findByName(name: String): Option[T] = macro ModalMacroImpl.find  
  11. }  

 

通过Modal及提供的macro,简化了model的定义。

ModalMacroImpl可以通过reflaction实现,并且macro是编译时增强的,不会对性能造成影响。

原文链接:http://www.software8.co/wzjs/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值