I am using Play2 with anom. I think the spirit of anorma writes simple sqls, without magic.
But I quickly discovered that I wrote a lot of similar dao methods. For instance:
case class User(id:Pk[String], username:String, email:String, realname:String, city:String, website:String) object User { val simple = get[Pk[String]]("id") ~ get[String]("username") ~ ... get[String]("website") map { case id ~ username ~ ... ~ website = User(id, username, ..., website) } def findByUsername(username:String) = DB.withConnection { implicit connection => SQL("select * from users where username={username}").on('username->username).as(simple.singleOpt) } def findByEmail(email:String) = DB.withConnection { implicit connection => SQL("select * from users where email={email}").on('email->email).as(simple.singleOpt) } def findById(id:String) = DB.withConnection { implicit connection => SQL("select * from users where id={id}").on('id->id).as(simple.singleOpt) } def findByRealname(keyword:String) = DB.withConnection { implicit connection => SQL("select * from users where realname like {keyword}").on('keyword->"%"+keyword+"%").as(simple *) } // more similar methods }
There the methods are almost the same, with the exception: where clause has a slight difference.
So, I created the findWhere() method as:
def findWhere(conditon, values:Any*) = ...
What can I call it in the actions:
User.findWhere("id=?", id) User.findWhere("username=?", username)
It works, but I don't think it is recommended by the abnormal.
What is the best way to solve this problem?
source share