Monday, April 14th, 2008

Joose expands with new ORM

Category: Gears, JavaScript

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

And some example usage:

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

Posted by Dion Almaer at 4:55 am
Comment here

+++--
3.3 rating from 17 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.