`
andyhu1007
  • 浏览: 193383 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

ActiveRecord的ORM问题域 Q&A

阅读更多

切尔斯基的ORM问题域 ,他提供了Hibernate的解答,现在来看看在ActiveRcord中是如何解决的。大多数解决方案都大同小异,但有些完全不同。

1. 加载根对象时如何避免加载大半个数据库

    同样,“更多的时候,这是一个建模问题”。使用eager load还是lazy load是用户的选择,根据特定场景而定。

 

    ActiveRecord和Hibernate一样,即可以在模型之间指定load方式,也可以在特定查询里面eager load,根据上句话,后者是更好的选择。

 

    Session per request, Open Session in View pattern

 

 

 

    Database Connection

 

     在非线程安全时,每个application instance都会被分配一个database connection。实现线程安全之后:

 

写道
Instead of a single database connection for a given Rails instance, there will be a pool of connections, allowing N database connections to be used by the M requests executing concurrently. It also means allowing requests to potentially execute without consuming a connection, so the number of live, active connections usually will be lower than the number of requests you can handle concurrently.
 

2. 存储时如何更新整个对象图

    切尔斯基已经做了解答:

切尔斯基 写道
框架支持级联更新. 是否应该级联更新, 哪些操作可以级联, 哪些不可以, 对象之间的哪些类型的关联可以级联, 哪些不可以, 则是程序员的责任。

3. 存储时如何高效地更新整个对象图

    答案未知。

 

4. 何时同步对象的内存状态和持久存储状态

    基本上在transaction commit的时候。另外reload方法也会导致内存状态和持久存储状态的更新。

 

5. 如何确保在出错时保持对象内存状态和持久存储状态之间的一致性

 

切尔斯基 写道
数据库事务回滚, 清空内存缓存, 重新加载

 

6. 如何保证引用的唯一性以避免可能的更新冲突

    这个答案跟Hibernate的实现有很大不同(至少目前,Rails2.3.6)

 

    ActiveRecord没有实现Identity Map。当然你要是想用,可以在这里找到一个简单实现:http://github.com/pjdavis/identity-map 。不过ActiveRecord的identity map好像已经在计划之中了。

 

    所以,如果两个对象持有同一个record,则互相并不会知道对方的存在。如下:

 

user1 = User.find(1)
user2 = User.find(1)

user1.update_attribute(:name => 'fuck')
user2.save  // 覆盖上个更新 

 

7. 性能优化问题

  1. N+1查询问题

  2. 分离查询模型和存储模型

  3. 尽量减少查询语句

    关于1和3,在我的这篇文章中有详细解释:http://huzhenbo.name/blog/2010/01/16/rails-performance-tuning

 

8. ActiveRecord Query Cache

写道
Query caching is a Rails feature that caches the result set returned by each query. If Rails encounters the same query again during the current request, it will used the cached result set as opposed to running the query against the database.

 

     ActiveRecord的query cache起到和Hibernate中的session一样的第一级缓存的作用。

 

Reference:

http://martinfowler.com/eaaCatalog/identityMap.html

http://takacsot.freeblog.hu/Files/martinfowler/identityMap.html

 

 

----EOF----

 

 

1
0
分享到:
评论
1 楼 andyhu1007 2010-04-07  
刚帮同事trouble shoot了一个问题:

def update
  if @deal.update_attributes(params[:deal])
    @deal.riders.each do |rider|
      p rider.detail
      p Details.last
      p Details.find_by_rider_id(rider.id)
  else
  ...
... 


条件:rider的detail是在update时新建的

问:上面三个输出各是什么,为什么?

相关推荐

Global site tag (gtag.js) - Google Analytics