数据映射代码还是反射代码?
将数据从数据库表获取到代码中的对象一直看起来像是普通的代码。 我发现有两种方法可以做到这一点:
- 使用一个代码生成器来读取数据库表并创建 类和控制器将数据字段映射到类字段,或
- 使用反射获取数据库字段并在类上查找它。
上述 2 种方法指出的问题如下所述。
- 方法 1 在我看来似乎遗漏了一些东西,因为我必须为每个表创建一个控制器。
- 当你处理大量数据时,方法 2 似乎太费力了 访问代码。
我是否应该尝试第三条路线将数据从数据库获取到我的对象上?
Getting data from a database table to an object in code has always seemed like mundane code. There are two ways I have found to do it:
- have a code generator that reads a database table and creates the
class and controller to map the datafields to the class fields or - use reflection to take the database field and find it on the class.
The problems noted with the above 2 methods are as noted below
- Method 1 seems to me like I'm missing something because I have to create a controller for every table.
- Method 2 seems to be too labor intensive once you get into heavy data
access code.
Is there a third route that I should try to get data from a database onto my objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下,您通常使用 OR(对象关系)映射器。 提供 OR 功能的一个很好的框架是 Hibernate。 这回答了你的问题了吗?
You normally use OR (Object-Relational) mappers in such situations. A good framework providing OR functionality is Hibernate. Does this answer your question?
我认为这个问题的答案取决于您将要使用的语言的可用技术。
我在使用 ORM (NHibernate) 方面非常成功,所以我自然会推荐选项一。
您可能还希望采用其他选项:
I think the answer to this depends on the available technologies for the language you are going to use.
I for one am very successful with the use of an ORM (NHibernate) so naturally I may recommend option one.
There are other options that you may wish to take though:
我使用反射来来回映射数据,即使在大量数据访问下它也能正常工作。 “第三条路线”是手动完成所有操作,这可能运行速度更快,但写入速度确实很慢。
I use reflection to map data back and forth and it works well even under heavy data access. The "third route" is to do everything by hand, which may be faster to run but really slow to write.
我同意 lewap 的观点,ORM(对象关系映射器)在这些情况下确实很有帮助。 您可能还需要考虑 Active Record 模式(在 Fowler 的《企业架构模式》一书中进行了讨论)。 它确实可以加快简单应用程序中 DAL 的创建速度。
I agree with lewap, an ORM (object-relational mapper) really helps in these situations. You may also want to consider the Active Record pattern (discussed in Fowler's Patterns of Enterprise Architecture book). It can really speed up creation of the DAL in simple apps.