Sunday, August 5, 2007

Object/Relational Mapping

Object/Relational Mapping

ORM libraries map database tables to classes. If a database has a table
called orders, our program will have a class named Order. Rows in this
table correspond to objects of the class—a particular order is represented as an object of class Order. Within that object, attributes are used to get and set the individual columns. Our Order object has methods to get and set the amount, the sales tax, and so on. In addition, the Rails classes that wrap our database tables provide a set of class-level methods that perform table-level operations. For example,
we might need to find the order with a particular id. This is implemented
as a class method that returns the corresponding Order object. In Ruby class method

order = Order.find(1) puts
puts "Order #{order.customer_id}, amount=#{order.amount}"
Sometimes these class-level methods return collections of objects.
iterating
Order.find(:all, :conditions => "name='dave'") do |order|
puts order.amount
end

Finally, the objects corresponding to individual rows in a table have methods
that operate on that row. Probably the most widely used is save( ), the
operation that saves the row back to the database.
Order.find(:all, :conditions => "name='dave'") do |order|
order.discount = 0.5
order.save
end

So an ORM layer maps tables to classes, rows to objects, and columns to
attributes of those objects. Class methods are used to perform table-level
operations, and instance methods perform operations on the individual
rows.
In a typical ORM library, you supply configuration data to specify the mappings
between things in the database and things in the program. Programmers
using these ORM tools often find themselves creating and maintaining
a boatload of XML configuration files.

No comments: