Data Object Coupling
A smart way to work with relational databases is to have Eiffel objects directly mapping relational tables. Three EiffelStore classes enable this coupling:
- DB_REPOSITORY objects describe a relational table and allow Eiffel to create objects mapping database tables.
- DB_STORE works directly with DB_REPOSITORY objects to insert data into relational tables .
- DB_SELECTION can map a database query result into Eiffel objects .
Describing relational tables with DB_REPOSITORY
A DB_REPOSITORY object stores available information about a table. To access this information, you mainly have to give the table name and load the table description: repository: DB_REPOSITORY ... create repository.make ("CONTACTS") repository.load if repository.exists then ... end
Using the table information, DB_REPOSITORY then helps generating Eiffel classes mapping relational tables:
- You can directly use {DB_REPOSITORY }.generate_class. Generated class may look like:
class CONTACTS feature -- Access id: INTEGER ... feature -- Settings set_id (an_id: INTEGER) -- Set an_id to id. do id := an_id end ...
Inserting data in the database
DB_STORE lets you easily insert rows into a table using:
- the table description provided by DB_REPOSITORY .
- a class mapping the relational table.
This is straight-forward since you only have to give DB_STORE the object filled with the table values. Suppose you want to add a contact into your database: storage: DB_STORE contacts_rep: DB_REPOSITORY a_contact: CONTACTS ... create storage.make -- contacts_rep is loaded and exists. storage.set_repository (contacts_rep) -- a_contact carries values to insert into the database. storage.put (a_contact)
Accessing database content with Eiffel objects
DB_SELECTION lets you map data retrieved from the database into Eiffel objects: Result column names must match object attributes names so you can use for instance classes created by DB_REPOSITORY . Class DB_ACTION
redefines ACTION and can be used to retrieve Eiffel objects directly into an ARRAYED_LIST: selection: DB_SELECTION list_filling: DB_ACTION [CONTACTS] contact: CONTACTS ... selection.object_convert (contact) create list_filling.make (selection, contact) selection.set_action (list_filling) ... selection.load_result if selection.is_ok then Result := list_filling.list end