Guest User

Untitled

a guest
Feb 20th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. package cn.orz.pascal.persistance
  2.  
  3. import com.db4o.{Db4o, ObjectContainer}
  4. import com.db4o.query.Predicate
  5.  
  6. import scala.collection.jcl.Conversions.convertList
  7.  
  8. object Db4oDao {
  9. implicit def toPredicate[E](predicate:(E) => Boolean) = new Predicate[E](){ def `match`(x:E) = predicate(x) }
  10.  
  11. var db:ObjectContainer = null
  12. var path = "sample.db"
  13.  
  14. def source() = db
  15.  
  16. def open(){
  17. db = Db4o.openFile(path)
  18. }
  19. def close(){
  20. db.close()
  21. db = null
  22. }
  23.  
  24. def config = Db4o.configure()
  25.  
  26. def isTransaction = db != null
  27.  
  28. def $[E](callback: => E):E = {
  29. if(isTransaction){
  30. callback
  31. }else{
  32. transaction{ callback }.asInstanceOf[E]
  33. }
  34. }
  35.  
  36. def get[E <: Model](id:Long):E = {
  37. ${
  38. val o:E = (db.ext().getByID(id)).asInstanceOf[E]
  39. db.activate(o, 5)
  40. o.id = id
  41. o
  42. }
  43. }
  44.  
  45. def delete[E <: Model](id:Long) = {
  46. ${
  47. db.delete(get[E](id))
  48. this
  49. }
  50. }
  51.  
  52. def store(o:Model) = {
  53. ${
  54. if(db.query((t:Model) => o == t).length == 0) db.store(o)
  55. this
  56. }
  57. }
  58.  
  59. def update[E <: Model](id:Long)(callback:(E)=>Unit) = {
  60. ${
  61. val o = get[E](id)
  62. callback(o)
  63. store(o)
  64. }
  65. }
  66.  
  67. def query[E <: Model](predicate:(E) => Boolean):List[E] = {
  68. ${
  69. db.query(predicate).toList.asInstanceOf[List[E]].map{ o => o.id = db.ext.getID(o); o}
  70. }
  71. }
  72.  
  73. def transaction(callback: => Any) = {
  74. var r:Any = null
  75. open()
  76. try{
  77. r = callback
  78. db.commit()
  79. }catch {
  80. case e: Exception => {
  81. db.rollback()
  82. throw e
  83. }
  84. }finally{
  85. close()
  86. }
  87. r
  88. }
  89. }
Add Comment
Please, Sign In to add comment