Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
- }
Add Comment
Please, Sign In to add comment