Created
November 9, 2008 13:50
-
-
Save koduki/23288 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cn.orz.pascal.persistance | |
import com.db4o.{Db4o, ObjectContainer} | |
import com.db4o.query.Predicate | |
import scala.collection.jcl.Conversions.convertList | |
object Db4oDao { | |
implicit def toPredicate[E](predicate:(E) => Boolean) = new Predicate[E](){ def `match`(x:E) = predicate(x) } | |
var db:ObjectContainer = null | |
var path = "sample.db" | |
def source() = db | |
def open(){ | |
db = Db4o.openFile(path) | |
} | |
def close(){ | |
db.close() | |
db = null | |
} | |
def config = Db4o.configure() | |
def isTransaction = db != null | |
def $[E](callback: => E):E = { | |
if(isTransaction){ | |
callback | |
}else{ | |
transaction{ callback }.asInstanceOf[E] | |
} | |
} | |
def get[E <: Model](id:Long):E = { | |
${ | |
val o:E = (db.ext().getByID(id)).asInstanceOf[E] | |
db.activate(o, 5) | |
o.id = id | |
o | |
} | |
} | |
def delete[E <: Model](id:Long) = { | |
${ | |
db.delete(get[E](id)) | |
this | |
} | |
} | |
def store(o:Model) = { | |
${ | |
if(db.query((t:Model) => o == t).length == 0) db.store(o) | |
this | |
} | |
} | |
def update[E <: Model](id:Long)(callback:(E)=>Unit) = { | |
${ | |
val o = get[E](id) | |
callback(o) | |
store(o) | |
} | |
} | |
def query[E <: Model](predicate:(E) => Boolean):List[E] = { | |
${ | |
db.query(predicate).toList.asInstanceOf[List[E]].map{ o => o.id = db.ext.getID(o); o} | |
} | |
} | |
def transaction(callback: => Any) = { | |
var r:Any = null | |
open() | |
try{ | |
r = callback | |
db.commit() | |
}catch { | |
case e: Exception => { | |
db.rollback() | |
throw e | |
} | |
}finally{ | |
close() | |
} | |
r | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment