Mapping
org.mybatis.scala.mapping
is the main package of the API, this provides all idioms needed to
declare ResultMaps and Statements.
ResultMap
To declare a ResultMap, just extend ResultMap[T] and call its mapping methods in its main constructor.
val personResultMap = new ResultMap[Person] { id ( property="id", column="pid" ) result ( property="name" column="full_name" ) }
You can define contructor args, properties, associations, collections, discriminators, ... Look at the scaladoc for furter details of ResultMap construction.
You can declare your ResultMaps wherever you want, you will reference them later when you declare your mapped statements.
Mapped Statements
There are four types of Mapped Statements as you know: Select, Insert, Update and Delete. But Select is a special case with three subtypes: SelectOne, SelectList and SelectMap.
To define/declare a mapped statement you just have to extend one of the Statement types and set the desired properties.
Select
For example, if you want to select a User by its id:
val findUserById = new SelectOneBy[Int,User] { def xsql = <xsql>SELECT * from user WHERE id = {"id"?}</xsql> } // this is also valid val findUserById = new SelectOneBy[Int,User] { def xsql = <xsql> SELECT * FROM user WHERE id = {"id"?} </xsql> }
You can also select a list of users filtered by its name
val findUsers = new SelectListBy[String,User] { def xsql = <xsql> SELECT * FROM user WHERE name LIKE {"name"?} </xsql> }
Insert, Update, Delete
The same applies to these statement types, just extends and define.
Example
val insertNewUser = new Insert[User] { keyGenerator = JdbcGeneratedKey(null, "id") def xsql = <xsql> INSERT INTO user(name, username, password) VALUES ({"name"?}, {"username"?}, {"password"?}) </xsql> }
All the mapping code is disconnected, so you can put it in a static initializer (scala object) or wherever you want.
Parameter binding syntax
There are two syntaxes: Textual notation and Scala notation, lets see
Textual notation
The former mybatis notation can be used here escaping '{' and '}' chars.
SELECT * FROM .... WHERE field = #{{param}}
SELECT * FROM .... WHERE field = #{{param, jdbcType=VARCHAR, mode=IN}}
Scala notation
You can import org.mybatis.scala.mapping.Binding._ and use the ? function. It provides type safety on binding attributes.
SELECT * FROM .... WHERE field = {"param"?}
SELECT * FROM .... WHERE field = {? ("param", jdbcType=JdbcType.VARCHAR, mode=ModeIN, typeHandler=T[CustomTHandler]) }