Here is the sample code that I have been using to persist some simple
objects:
To write persistent objects
require 'java'
require 'employee'
require 'persistence'
include Persistence
persistent 'people'
person = Person.new('Alan')
employee = Employee.new('Bob', 12345)
@people.store(person)
@people.store(employee)
person.children = Array.new
employee.children = Array.new
person.add_child(Person.new('Jesse'))
person.add_child(Person.new('Blake'))
employee.add_child(Person.new('Ben'))
@people.commit
puts 'Committed people'
To read persistent objects (in another VM)
require 'java'
require 'employee'
require 'persistence'
include Persistence
persistent 'people'
person = @people.fetch(0)
employee = @people.fetch(1)
puts 'Person name = ' + person.name
person.children.each {|child| puts 'child = ' << child.name}
puts
puts 'Employee name = ' + employee.name
puts 'Employee ssn = ' + employee.ssn.to_s
employee.children.each {|child| puts 'child = ' << child.name }
Here is the Persistence module
Note: the Indexable module and the extension to Array and Hash are
only there to add an 'p_id' field for fetching by id in the example
above
They will probably go away:
module Indexable
def store_by_id(object)
unless object.p_id
object.p_id = self.size
end
self[object.p_id] = object
end
end
class Array
include Indexable
end
class Hash
include Indexable
end
class PersistentRoot
def initialize(indexable = Hash.new, options = {})
@options = options
@objects = indexable
end
def fetch(p_id, conditions = {})
@objects[p_id]
end
def store(object)
unless @@session.getTransactionService.inTransaction
@@session.getTransactionService.beginTransaction
end
@objects.store_by_id(object)
end
def store!(object)
unless @@session.getTransactionService.inTransaction
@@session.getTransactionService.beginTransaction
end
@objects.store_by_id(object)
commit
end
def commit
@@session.commit
end
end
module Persistence
def self.included(otherModule)
@@session = GsSessionImpl.getImpl
(SessionFactory.getInstance.createNonPooledSession)
end
def persistent(name)
rootObject = nil
begin
rootObject = @@session.getInitialContext.lookup(name)
rescue
@@session.begin
rootObject = PersistentRoot.new
@@session.getInitialContext.bind(name, rootObject)
@@session.commit
end
instance_variable_set('@' + name, rootObject)
end
end
Finally, the Person and its includes
module PID
def p_id=(num)
@p_id = num
end
def p_id
@p_id
end
end
module Family
def children=(children)
@children = children
end
def children
@children
end
def add_child(child)
@children << child
end
end
class Person
include PID
include Family
def initialize(name)
@name = name
end
def name
@name
end
end