数据库中的数据带来的诱惑

平常开发的后台服务会有一个数据库在最底层,而最外层对客户端提供一个 Restful 接口。

在这两个层次中会定义最重要的数据结构:

  • 数据库表结构
  • HTTP 请求响应体的结构

这两个层次中的相同事务往往会定义地非常相似,我们会忍不住共用它们,或者是强烈地渴望它们保持一致。这带了的一个好处是形式上很优美(统一就是美),还有就是中间不需要做任何处理或适配,客户端请求中的数据可以直接用于数据库操作,数据库中取出的数据可以直接用于响应客户端请求。ORM(Object relational mapping)就是这种思想的产物,《ORM is evil | Echo One》一文对这种想法进行了驳斥:

Worse, it allows people to not think of database as being a collection of, y’know, relational data but instead as being a list of entities.

The biggest problem with programmers seeing the database through the ORM reality-distortion filter is that they start thinking that the entities they deal with are the data. In most cases that simply isn’t true, or if it is it is because the entities have started to become some kind of uber-object that contains everything about everything.

You use queries to constitute a coherent and logical projection of the underlying data that can be defined by the purpose the data is going to be used for.

ORM should see itself as just being one consumer of data and learn to play better with others. It should be about the convenience of presenting one valid method of data modelling in a form that is more familiar to programmers. It should take away any impedance due to having to comprehend the relational model (which I admit is hard) but it should leave it there and stop thinking that is the true answer to complex data issues.

太坏了,它让人意识不到数据库是关系数据的集合,误以为是实体的集合。

最大的问题是程序员透过 ORM 的变形滤镜去看数据库后,

会认为数据库中的数据就是要处理的实体。

大多数情况下这不是真的,或这些“实体”成了包罗万象的对象。

你应该针对数据的用途,从数据库中查询出相应的内聚逻辑实体。

ORM 应该将自已看做是众多的数据消费者中的一个,学会和其它消费者共存。

要意思到 ORM 只是便捷而有效的一种数据建模方式,被程序员所熟知。

ORM 需要理解关系模型,会对数据库设计本身带来了阻力,这是不应该的,

面对复杂数据这一难题,不要指望 ORM。

我们应该意识到数据库中的数据和客户端需要的“数据”是不同的,数据库中的数据就像你放在冰箱里的食材,而用户想要的是丰盛的大餐,而后台服务需要根据客户的要求利用数据库中的食材做出一道道大餐。