Activate your free membership today | Log-in

Monday, April 14th, 2008

Joose expands with new ORM

Category: Gears, JavaScript

Malte has continued to work on Joose, his meta object system for JavaScript. He has added a lot of documentation, including cookbooks that tell the story nicely. He also told us about a feature that is near and dear to my Google heart:

Joose now includes a simple object relational mapper for the Gears database in the examples section. If you have Gears installed, you can run it.

It will run its test suite and then display a class browser that displays the contents of a table for classes that represent a database
tables. The example has two entities (Car and Person in the MyEntities module).

Declaring the entities with this proof-of-concept OR-mapper looks like
this:

JAVASCRIPT:
  1.  
  2. Module("MyEntities", function (m) {
  3.  
  4.    Class("Car", {
  5.        isa:  ORM.Entity,
  6.  
  7.        has: {
  8.            owner: {
  9.                metaclass: ORM.HasOne,
  10.                isa:       function () { return m.Person }
  11.            }
  12.        },
  13.  
  14.        classMethods: {
  15.            tableName: function () {
  16.                return "car"
  17.            }
  18.        }
  19.    })
  20.  
  21.    Class("Person", {
  22.        isa:  ORM.Entity,
  23.  
  24.        classMethods: {
  25.            tableName: function () {
  26.                return "person"
  27.            }
  28.        },
  29.  
  30.        has: {
  31.            mother: {
  32.                metaclass: ORM.HasOne,
  33.                isa:       function () { return m.Person }
  34.            },
  35.  
  36.            cars: {
  37.                metaclass:  ORM.HasMany,
  38.                isa:        function () { return m.Car },
  39.                foreignKey: "owner"
  40.            }
  41.        }
  42.    });
  43. });
  44.  

And some example usage:

JAVASCRIPT:
  1.  
  2. // Create the mother
  3. var mother = new MyEntities.Person();
  4. mother.name("elke");
  5. mother.city("Elmshorn");
  6. mother.save();
  7.  
  8. // Create the son
  9. var person = new MyEntities.Person();
  10. person.name("malte");
  11. person.city("Hamburg");
  12. person.mother(mother); // set the mother
  13. person.save();
  14.  
  15. // Give the son 10 cars :)
  16. for(var i = 0; i <10; i++) {
  17.     var car = new MyEntities.Car();
  18.     car.model("3."+i);
  19.     car.brand("bmw");
  20.     car.owner(person);
  21.     car.save();
  22. }
  23.  
  24. // refetch the person from the db
  25. var personFromDb = Entities.Person.newFromId(person.rowid());
  26.  
  27. alert(personFromDb.mother().name()) // will alert 'elke'
  28. alert(personFromDb.cars()[0].brand()) // will alert 'bmw'
  29.  

Posted by Dion Almaer at 4:55 am

+++--
3.4 rating from 12 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.