DB with anorm

scala 2016. 3. 2. 16:58

scala에서 DB를 연동할 때, JDBC를 직접 사용할 수도 있지만

Play Framework와 함께 할때는 Anorm을 사용하는 방법이 편리하다.


REF-SITE :play



사용모습을 보면 아래와 같다.



(예제: 출처 https://janhelwich.wordpress.com/tag/anorm/ )

object Post{
  val parser = {
      get[String]("title") ~
      get[Date]("posted") ~
      get[String]("content")~
      get[Pk[Int]]("authorId") map {
      case title ~ posted ~ content ~ author => Post(title,  posted, content, User.findBy(author))
    }
  }
 
  def findAll() = {
    DB.withConnection {
      implicit connection =>
        SQL("select * from posts").as(parser *)
    }
  }
 
  def create(post: Post): Unit = {
    DB.withConnection {
      implicit connection =>
        SQL("insert into posts(title, posted, content, authorId) values ({title}, {posted}, {content}, {authorId})").on(
          'title -> post.title,
          'posted -> post.posted,
          'content -> post.content,
          'authorId -> post.author.id
        ).executeUpdate()
    }
  }


Posted by yongary
,