Jump to content

Active record pattern

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by AIOS (talk | contribs) at 02:17, 2 October 2006 (linked to View_(database) (view is ambiguous, could be MVC view..)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

One of the widely-used 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.

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();
}