2012-02-21 2 views
4

私は暴風雨でPlay2を使用しています。私は、嵐の精神は背後にある魔法のない平易な平方キロを書いていると思う。多くの似たような方法が暴風雨にあります。

しかし、私はすぐに同様のDAOメソッドをたくさん書いていることがわかりました。たとえば:

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 
} 

そこの方法はほぼ同じ、例外where節は小さな違いがあります。

だから私はとしてfindWhere()方法作成:それは作品

User.findWhere("id=?", id) 
User.findWhere("username=?", username) 

が、私はそれはanormでお勧めしますとは思わない:私はアクションでそれを呼び出すことができ

def findWhere(conditon, values:Any*) = ... 

を。

この問題を解決するにはどうすればよいですか?

答えて

3

なぜあなたはそれが推奨されていない、またはOKではないと思いますか?

Anormは、SQLクエリを受信し、その結果をケースクラスに解析することのみを気にします。あなたの制約/設計のために、そのSQL要求をdinamically生成するならば、それは何の違いもありません。

私が見ている唯一の問題は彼のものですか? char、これはAnormのやり方です。

User.findWhere("username", username) 

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

これは簡単な例で、必要に応じて拡張します。

+1

これはSQL文字列を使用しますが、どのようにそれらの文字列を作成するかは、それとは無関係です。あるいは、私はあなたのことを理解していないでしょう! :) –

関連する問題