zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    loadrunner提高篇
    loadrunner提高篇
    loadrunner提高篇
    STM32F4XX高效驱动篇1-UART
    系统封装接口层 cmsis_os
    uCGUI 按键窗口切换机制
    xming+xshell让linux变成桌面化操作
    jmeter做WebSocket请求解读
    性能监控工具spotlight操作
    linux性能监控命令,磁盘,网络,cpu,内存
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3015582.html
Copyright © 2011-2022 走看看