play2 에서 Anorm 으로 PostgreSQL 사용하기
* 일단 IntelliJ 에 play2 개발 환경이 갖춰져 있다는 전제입니다.
* play 2.48 ( 최신은 2.5 이나 정보를 찾는 면에서 있어서 어려움이 있다)
* anorm 2.5
* posgresql driver 9.3-1102-jdbc41
1. application.conf
- DB 접근 설정을 합니다.
db.default.url="jdbc:postgresql://userip/DatabaseName"db.default.username= your user
db.default.password= your password
db.default.driver=org.postgresql.Driver
2. build.sbt 에서
- JDBC postgresql 라이브러리에 대한 종속성을 추가해줍니다. 자동으로 다운로드 받습니다.
- postgresql 드라이버 버전이 "9.1-901.jdbc4" 로 안되서 올렸더니 잘 됩니다.
libraryDependencies ++= Seq(
jdbc ,
"com.typesafe.play" %% "anorm" % "2.5.0",
cache ,
ws ,
specs2 % Test,
"org.postgresql" % "postgresql" % "9.3-1102-jdbc41")
3. 코딩
- 모델 클래스 작성
case class Thing (
thing_id : Int,
name : String
)
* Anorm 다루기 (MyBatis 에 가까운 놈임, Slick 나 Squeryl 이 ORM. 개인적으로 ORM 은 별로 같아요..)
(참고로 DB.withConnection 은 최근 버전에서는 deprecated 됬습니다만... 옛날버전이 자료가 많아요 OTL )
1) 스트림 API 사용해서 데이터 가져와서 객체에 담기
def findThingByID_streaming(id : Int): List[Thing] = DB.withConnection {
implicit connection =>
val sql: SqlQuery = SQL("select * from tbl_thing_info where thing_id = {id}")
sql.on("id" -> id)
sql().map ( row =>
Thing(row[Int]("thing_id"), row[String]("name"))
).toList
}
2) paser 를 이용해서 데이터 가져와서 객체에 담기
val thingParser: RowParser[Thing] = {
int("thing_id") ~ str("name") map {
case thing_id ~ name =>
Thing(thing_id, name)
}
}
import anorm.ResultSetParser
val thingsParser: ResultSetParser[List[Thing]] = {
thingParser *
}
def findThingByID_parser(id : Int): List[Thing] = DB.withConnection {
implicit connection =>
val sql = SQL("select * from tbl_thing_info where thing_id = {id}").on("id" -> id)
sql.as(thingsParser)
}
p.s
ORM 경우는 Slick 이 있는데 개인적으로 ORM 을 좋아하지 않아서 사용안한다. 대략적인 사용법은 아래에 정리함.
예제로 보는 아카(akka) - 14. Slick 으로 PostgreSQL 사용하기
참고 :https://www.playframework.com/documentation/2.4.x/ScalaAnorm
'PlayFramework2' 카테고리의 다른 글
| Anorm 2.5 (2) - Anorm 시작하기 (0) | 2016.08.26 |
|---|---|
| Anorm 2.5 (1) - Anorm 이란 ? (0) | 2016.08.26 |
| Deploy Play 2.4 (Scala) on Amazon EC2 [Simple] (0) | 2016.08.11 |
| Play2 시작하기 - IntelliJ (0) | 2016.08.03 |
| Play2 설치하기 (with Activator, Scala, Windows, Eclipse) (0) | 2016.08.02 |