Created
March 12, 2014 23:53
-
-
Save cvogt/9519186 to your computer and use it in GitHub Desktop.
Nested entity mapping with Slick 1.x
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
case class Part1(i1: Int, i2: String) | |
case class Part2(i1: String, i2: Int) | |
case class Whole(p1: Part1, p2: Part2) | |
class Tuple2Mapper[Entity,Component1,Tuple1,Component2,Tuple2]( | |
entityFactory: (Component1,Component2) => Entity, | |
entityExtractor: Entity => Option[(Component1,Component2)], | |
component1factory: Tuple1 => Component1, | |
component1extractor: Component1 => Option[Tuple1], | |
component2factory: Tuple2 => Component2, | |
component2extractor: Component2 => Option[Tuple2] | |
){ | |
def apply( tuple1: Tuple1, tuple2: Tuple2 ) = | |
entityFactory(component1factory(tuple1), component2factory(tuple2)) | |
def unapply(entity: Entity) = entityExtractor(entity).map(tuple => ( | |
component1extractor(tuple._1).get, | |
component2extractor(tuple._2).get | |
)) | |
} | |
object WholeMapper extends Tuple2Mapper( | |
Whole, | |
Whole.unapply, | |
Part1.tupled, | |
Part1.unapply, | |
Part2.tupled, | |
Part2.unapply | |
) | |
object T extends Table[(Int,String,String,Int)]("t_nested") { | |
def p1 = column[Int]("p1") | |
def p2 = column[String]("p2") | |
def p3 = column[String]("p3") | |
def p4 = column[Int]("p4") | |
def * = p1 ~ p2 ~ p3 ~ p4 | |
def nested = ((p1,p2), (p3,p4)) | |
} | |
val data = Seq( | |
Whole( | |
Part1(1, "2"), | |
Part2("3", 4) | |
) | |
) | |
T.ddl.create | |
T.nested.shaped.insertAll(data.map(WholeMapper.unapply(_).get):_*) | |
assertEquals(data, Query(T).map(_.nested).run.map((WholeMapper.apply _).tupled)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment