Active Record Pattern

From Wikipedia, the free encyclopedia

In [computer science]( "Computer science"), the active record pattern is a [design pattern]( "Design pattern (computer science)") frequently found in software that stores its data in [relational databases]( "Relational database"). It was named by [Martin Fowler]( "Martin Fowler") in his book Patterns of Enterprise Application Architecture.

Active record is an approach to accessing data in a [database]( "Database"). A [database table]( "Database table") or [view]( "View (database)") is wrapped into a [class]( "Class (computer science)"), thus an [object]( "Object (computer science)") instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the table is also updated. The [wrapper class]( "Wrapper class") implements [accessor]( "Accessor") [methods]( "Methods") or properties for each column in the table or view.

This pattern is commonly used by object persistence tools, and in [object-relational mapping]( "Object-relational mapping"). Typically [foreign key]( "Foreign key") relationships will be exposed as an object instance of the appropriate type via a property.

Implementations of Active Record can be found in various [frameworks]( "Framework") for many programming environments. For example, if in a database there is a table parts with columns name (string type) and price (number type), and the Active Record pattern is implemented in the class Part, the following pseudo-code:

part = new Part() = "Sample part" part.price = 123.45

will create a new row in the parts table with the given values, and is roughly equivalent to the [SQL]( "SQL") command

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

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

b = Part.find_first_part("name", "gearbox")

This will create a new Part object based on the first matching row from the parts table whose name column has the value "gearbox". The SQL command used would be

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

Để đó, chưa dịch :(