Java N Coffee

Friday, January 12, 2007

Active Record Java

Impressed by the ActiveRecord concept in Rails/Martin Fowler, I tried to develop something of the same kind in Java called "Active Record Java".

The things that I liked are:->
  1. No XML requirement for mapping of classes and tables.
  2. Dynamic nature for agile development.
  3. Shell prompt to evaluate pieces of code fast (irb).
  4. Class file clean for business logic (validation code though present I find it clean).
Till now what I have accomplished is R of CRUD. I used Innodb type tables In MySql not done in any other DB.

You have to name your classfile same as your table name.
eg: Parent => parent table.

You have to give just the database name and you are ready.You don't need to define variables like "private String name" , during startup metadata is read from the database and also the relationships between tables of type 1..*.With metadata I keep the track of all the variables and their datatype.
eg:

parent table:->
id | int(11) | PRI
name | varchar(15)
address | varchar(100)

The class Parent will have

public class Parent extends ActiveRecordJava{

public Parent(){}

}


the methods that I have been able to implement are

static find

Parent parent = (Parent)find("parent","1");

this will take string "parent" the table name and the next id i.e 1
and return instance of Parent class.

to access fields you have to make a call like......

parent.get("name");
parent.get("address");

There is 1..* relation between parent and child table.
This you dont need to define anywhere in class file.
Both Parent and Child class file are clean.

Child child = (Child)find("child", "1");
Parent p=(Parent)child.belongsTo("parent");

to get the other side i.e all children of parent.
p.listOfAll("child") will return arraylist of all values.

Only thing that you have to write is for *..* as it doesn't makes sense for detecting this kind of relation from metadata.You will have to initialize the relation in constructor.

public Products() {
markMany("customers","through:customers_products");
}

to get arraylist of customers

Products products = (Products)find("products","1");
products.hasMany("customers");

usage:->
ArrayList<Customers> cst = products.hasMany("customers");
Customers c1 = cst.get(0);


till now I have implemented these things and trying for many other things hope so i'll finish CRUD fast.

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home