Is there a relationship between Database Tables an

2019-05-26 01:34发布

问题:

Every time I program I recognize this relationship between classes and tables, or am I imagining it.

You can have a class per database table or a table per class i.e. :

    tables: customer, products, order.

    classes: customer, products, order, may have methods such as addRecord, deleteRecord, updateRecord.

what is this called? Object-Relational? I am not a DBA.

回答1:

It all depends on the type of database you're using. If you're using an object oriented database (OODB), then there is no relationship, as the objects and the persisted data are the same thing. For example, if you have a Customer class, and you save it in an OODB, then that instance of the customer is what is stored in the DB.

If you are using a relational database, then the class instances, and the persisted representation of them in the DB, can be the same thing, but many times they aren't. This is because most folks use normalization to represent their data in an efficient way (in a relational DB). This means, instead of having a table per class, you can have a class represented by more than one table. In the Customer example, the tables might now be Customer (with Name, date of birth, and other properties), and Order (with order pointing to products in yet another table). The reason for this has to do with cardinality, and the ability for Customers to have more than one order. When your business logic needs this information from the DB, the data access layer's job is to map the data (called ORM) from the DB into your classes.

If you are using yet another type of DB, then there will be a different relationship between the classes (domain model) and what's persisted in the DB.

But, as far as having a name for this relationship? No, there is no name.



回答2:

In additon to Bob's answer, the following.

In object modeling, the relationship between classes and subclasses is taken care of by inheritance, and object modelers know how to use inheritance to good advantage. The relational data model and by extension the SQL databases do not implement inheritance for you. You have to design tables to give you some of the same results.

In ER (Entity-Relationship) modeling, the corresponding concept is called generalization/specialization. This tells you how to model a class/subclass relationship, but it doesn't tell you how to design the tables when you go to build your database.

There are three techniques that are pretty well understood that can be really helpful when dealing with classes and subclasses. Here are their tags: single-table-inheritance class-table-inheritance shared-primary-key. Unfortunately, many tutorials on database design never cover these techniques. They can be enormously useful to people who know object modeling and want to come up to speed on relational modeling.