There are many similar dao methods in anorm, right?

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?

+4
source share
1 answer

Why do you think this is not recommended or normal?

Anorm only cares about getting the SQL query and analyzing the result in the case class. If, due to your limitations / design, you generate a SQL query dynamically, it does not matter.

The only problem I see is he? char, which is not how Anorm works. I believe that I will like it more:

 User.findWhere("username", username) def findWhere(field: String, value: String) = { SQL("select * from users where "+ field +"={"+ field +"}").on(Symbol(field)->value).as(simple.singleOpt) } 

This is a simple example, expandable as needed.

+3
source

Source: https://habr.com/ru/post/1397533/


All Articles