Greetings,
I'm using jdbi for interfacing with mysql using Scala.
What is working: converting mysql results with single row in it to corresponding object using ResultMapper
What is not working: converting mysql results with multiple rows in it to corresponding object using ResultMapper
Issues encountered:
- (PersonMapper) Mapper used to convert queries with single row in result to Scala object cannot be used with the queries that return multiple rows (because of return type of functions)
- (PersonMapperList) Mapper to convert queries with multiple rows in result always gets only one row in the result set. Hence only one model is returned by mapper
model:
class Person(name:String, age: Int, color:String) {
override def toString = name + "," + age.toString + ", " + color
}
Result mapper
class PersonMapper extends ResultSetMapper[Person]
{
def map(index : Int, r:ResultSet, ctx:StatementContext) : Person = {
new Person(r.getString("Name"), r.getInt("Age"), r.getString("Favorite Color"))
}
}
trait QuerySample{
@SqlQuery("select * from anuragTest.trivia where name = :name")
@Mapper(classOf[PersonMapper])
def findByName(@Bind("name") name:String) : Person
@SqlQuery("select * from anuragTest.trivia")
@Mapper(classOf[PersonMapper])
def getAllRecords() : List[Person]
}
def main(args : Array[String]){
val dbi : DBI = new DBI("jdbc:mysql://localhost:3306", "root","somepassword")
val h = dbi.open()
val qs:QuerySample = h.attach(classOf[QuerySample])
println(qs.findByName("Bruce Callow")) //this query runs fine
val allPeople = qs.getAllRecords()
}
I get build error if i use the same PersonMapper to map one row result and multiple row result to Person object
com.experiments.TestMysqlConnection$Person cannot be cast to scala.collection.immutable.List
If i add another mapper to multiple results to list of person object and use @Mapper(classOf[PersonMapperList]) for getAllRecords
Result mapper for processing multiple result rows in query (ideally this shouldnt have been required)
class PersonMapperList extends ResultSetMapper[List[Person]]
{
def map(index : Int, r:ResultSet,ctx:StatementContext) : List[Person] = {
val buf = scala.collection.mutable.ListBuffer.empty[Person]
while(r.next()){
buf += new Person(r.getString("Name"), r.getInt("Age"), r.getString("Favorite Color"))
}
buf.toList
}
}
By using PersonMapperList, the ResultSet of map of PersonMapperList contains always only one object (its resultSet.next() is always false) - the query returns more than one record when run on terminal or through select query : val rs = h.select("select * from anuragTest.trivia"). So there is no issue with the query
There is no way I'm being to convert a query with multiple result rows to corresponding People object.
What wrong am i doing here? How do i proceed
Thanks!
Anurag