1+ package org .mybatis .scala .samples .select
2+
3+ import org .mybatis .scala .mapping .EnumStrTypeHandler
4+ import org .mybatis .scala .mapping .EnumIntTypeHandler
5+ import org .mybatis .scala .mapping .SelectList
6+ import org .mybatis .scala .mapping .ResultMap
7+ import org .mybatis .scala .mapping ._
8+ import org .mybatis .scala .samples .util .DBSchema
9+ import org .mybatis .scala .samples .util .DBSampleData
10+
11+ /*
12+ * sample enum
13+ */
14+ object GroupEnum extends Enumeration {
15+ val Customers = Value (1 , " Customers" )
16+ val Suppliers = Value (2 , " Suppliers" )
17+ val Employees = Value (3 , " Employees" )
18+ }
19+
20+ /*
21+ * sample case class to represent the selected records
22+ */
23+ case class Group (val id : Int , val name : String , val group : GroupEnum .Value )
24+
25+ /*
26+ * string based handler for GroupEnum
27+ */
28+ class GroupEnumStrTypeHandler extends EnumStrTypeHandler {
29+ def enumObj = GroupEnum
30+ }
31+
32+ /*
33+ * int based handler for GroupEnum
34+ */
35+ class GroupEnumIntTypeHandler extends EnumIntTypeHandler {
36+ def enumObj = GroupEnum
37+ }
38+
39+ /*
40+ * the queries
41+ */
42+ object GroupQueries {
43+ class Query (colName : String , typeHandler : T [_ <: TypeHandler [Enumeration # Value ]]) extends SelectList [Group ] {
44+ resultMap = new ResultMap [Group ] {
45+ arg(" id_" , javaType = T [Int ])
46+ arg(" name_" , javaType = T [String ])
47+ /*
48+ * an enum field, javaType is mandatory in this case since the typeHandler val is typed erased (or something...)
49+ */
50+ arg(colName, typeHandler = typeHandler, javaType = T [Enumeration # Value ])
51+ }
52+ def xsql = """
53+ SELECT
54+ id_, name_
55+ FROM
56+ people_group
57+ """
58+ }
59+ /*
60+ * the actual queries
61+ */
62+ val selectEnumViaString = new Query (" name_" , T [GroupEnumStrTypeHandler ])
63+ val selectEnumViaInteger = new Query (" id_" , T [GroupEnumIntTypeHandler ])
64+
65+ }
66+
67+ object SelectEnumSample extends App {
68+ // Do the Magic ...
69+ override def main (args : Array [String ]): Unit = {
70+ /*
71+ * this is a bit tricky, getting to register the statements before actually creating the Configuration object
72+ */
73+ CDB .ConfigurationSpec .statements(GroupQueries .selectEnumViaString, GroupQueries .selectEnumViaInteger)
74+ CDB .context.transaction { implicit s =>
75+
76+ // Create database and populate it with sample data
77+ DBSchema .create
78+ DBSampleData .populate
79+
80+ for (q <- Seq (GroupQueries .selectEnumViaString, GroupQueries .selectEnumViaInteger)) {
81+ // Query
82+ GroupQueries .selectEnumViaString().foreach(x => {
83+ println(x)
84+ // some basic tests
85+ assert(x.group != null )
86+ assert(x.group.id == x.id)
87+ assert(x.group.toString == x.name)
88+ assert(GroupEnum (x.id) == x.group)
89+ assert(GroupEnum .withName(x.name) == x.group)
90+ })
91+ }
92+ }
93+ }
94+ }
0 commit comments