오라클 드라이버로는 returning을 사용해서 multiple column을 가져오는 게 가능했는데, MySQL은 왜인지 적용이 안되고, insert문 자체가 실행이 안됨.
Last active
June 26, 2018 06:38
-
-
Save jungbin-kim/be771c77159b2ffdd822513abf401eda to your computer and use it in GitHub Desktop.
slick tabel mapping 자동 증가 컬럼 대응
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import slick.driver.MySQLDriver.api._ | |
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
object Tables { | |
// Connect with MySQL DB | |
val db = Database.forConfig("slick.dbs.target_db.db") | |
implicit val localDateTimeToDate = MappedColumnType.base[LocalDateTime, Timestamp]( | |
l => Timestamp.valueOf(l), | |
t => t.toLocalDateTime | |
) | |
lazy val tableTestTables = TableQuery[TableEntities] | |
type Raw = (Option[Int], String, String, Option[LocalDateTime]) | |
def construct: Raw => TestTable = { | |
case (Some(id), desc, uuid, Some(created)) => TestTable(id, desc, uuid, created) // SELECT | |
} | |
def extract: PartialFunction[TestTable, Raw] = { | |
case TestTable(-1, desc, uuid, _) => (None, desc, uuid, None) // INSERT | |
case TestTable(id, desc, uuid, created) => (Some(id), desc, uuid, None) // UPDATE | |
} | |
class TableEntities(tag:Tag) extends Table[TestTable](tag, "tbl_test") { | |
def id = column[Int]("id", O.PrimaryKey, O.AutoInc) | |
def desc = column[String]("desc") | |
def uuid = column[String]("uuid") | |
def created = column[LocalDateTime]("created", O.AutoInc) | |
override def * = (id.?, desc, uuid, created.?) <> (construct, extract.lift) | |
} | |
// return 할 때, id 외에 created도 하면 isert가 안됨. id | |
def create(desc: String, uuid: String): Future[Option[TestTable]] = { | |
val insertQuery = tableTestTables | |
.returning(tableTestTables.map(_.id)) | |
.into((item, auto) => item.copy(id = auto)) | |
for { | |
inserted <- db.run(insertQuery += TestTable(-1, desc, uuid, LocalDateTime.now)) | |
createdData <- db.run(tableTestTables.filter(d => d.id === inserted.id).result.headOption) | |
} yield createdData | |
} | |
} | |
case class TestTable( | |
id: Int, | |
desc: String, | |
uuid: String, | |
created: LocalDateTime | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment