Active record pattern

From Wikipedia, the free encyclopedia

In computer science, the active record pattern is a design pattern frequently found in enterprise applications.

Active record is an approach to reading data from a database. A row in a database table or view is wrapped into a class, thus an object instance is tied to a single row in the database. After creation of an object, a new row is added to the database upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the database is also updated. The wrapper class implements accessor methods for each column in the table or view.

The active record approach is found in xBase languages like dBase and Clipper, where it is called a workarea. One of the newer implementations is the Active Record implementation found in Ruby on Rails. For example, if there's a table parts with columns id (serial primary key), name (varchar type) and price (money or double precision type), and there's a class Part, the following code,

a = Part.new
a.name = "Sample part"
a.price = 123.45
a.save

will create a new row in the database with the given values, and is roughly equivalent to the SQL command

INSERT INTO parts (name, price) VALUES ('Sample part', 123.45);

Conversely, the class can be used to query the database:

widgetname = "gearbox"
b = Part.find(:first, :conditions => [ "name = ?", widgetname ])

will create an object from the first row of the database whose name column is equal to the contents of the Ruby variable widgetname, and is roughly equal to the SQL command

SELECT * FROM parts WHERE name = 'gearbox' LIMIT 1;

Alternatively, the above code could have been shortened:

b = Part.find_by_name("gearbox")

A LINQ based complex object query using a where clause to filter persons by age. <More explanation needed here: is this a Microsoft implementation of the Active Record pattern?>

static void ObjectQuery()
{
    var people = new List<Person>() {
        new Person { Age=12, Name="Bob" }, 
        new Person { Age=18, Name="Cindy" },
        new Person { Age=13, Name="Michael" }
    };
                        
    var teenagers = 
        from p in people
        where p.Age > 12 && p.Age < 20
        select p;
                        
    Console.WriteLine("Result:");
    foreach(var val in teenagers)
    {
        Console.WriteLine("> Name = {0}, Age = {1}", val.Name, val.Age);
    }
                        
    Console.ReadLine();
}

[edit] External links

In other languages