Skip to content

Commit 00d537e

Browse files
committed
TypeHandler traits for enums, this can be mixed into a concrete class (supplying the enum object) to create a fully functional typeHandler.
1 parent 4e533df commit 00d537e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package org.mybatis.scala.mapping
2+
3+
import org.apache.ibatis.`type`.BaseTypeHandler
4+
import java.sql.ResultSet
5+
import java.sql.PreparedStatement
6+
import java.sql.CallableStatement
7+
import org.apache.ibatis.`type`.StringTypeHandler
8+
import org.apache.ibatis.`type`.IntegerTypeHandler
9+
10+
trait EnumTypeHandlerBase[I] extends BaseTypeHandler[Enumeration#Value] {
11+
12+
final def setNonNullParameter(ps: PreparedStatement, i: Int, parameter: Enumeration#Value, jdbcType: org.apache.ibatis.`type`.JdbcType) = {
13+
val x = toIntermediateRepr(parameter)
14+
intermediateTypeHandler.setParameter(ps, i, x, jdbcType)
15+
}
16+
17+
final def getNullableResult(rs: ResultSet, columnName: String) = {
18+
Option(intermediateTypeHandler.getResult(rs, columnName)).map(fromIntermediateRepr).orNull
19+
}
20+
21+
final def getNullableResult(rs: ResultSet, columnIndex: Int) = {
22+
Option(intermediateTypeHandler.getResult(rs, columnIndex)).map(fromIntermediateRepr).orNull
23+
}
24+
25+
final def getNullableResult(cs: CallableStatement, columnIndex: Int) = {
26+
Option(intermediateTypeHandler.getResult(cs, columnIndex)).map(fromIntermediateRepr).orNull
27+
}
28+
protected def enumObj: Enumeration
29+
protected def intermediateTypeHandler: TypeHandler[I]
30+
protected def toIntermediateRepr(notNull: Enumeration#Value): I
31+
protected def fromIntermediateRepr(notNull: I): Enumeration#Value
32+
}
33+
34+
trait EnumStrTypeHandler extends EnumTypeHandlerBase[String] {
35+
final protected val intermediateTypeHandler = new StringTypeHandler
36+
final protected def toIntermediateRepr(notNull: Enumeration#Value) = notNull.toString
37+
final protected def fromIntermediateRepr(notNull: String) = enumObj.withName(notNull)
38+
}
39+
40+
trait EnumIntTypeHandler extends EnumTypeHandlerBase[Integer] {
41+
final protected val intermediateTypeHandler = new IntegerTypeHandler
42+
final protected def toIntermediateRepr(notNull: Enumeration#Value) = notNull.id
43+
final protected def fromIntermediateRepr(notNull: Integer) = enumObj(notNull.intValue)
44+
}

0 commit comments

Comments
 (0)