English 中文(简体)
我如何在多个DDD存储库中有效使用SQLAlchemy?
原标题:How do I effectively use SQLAlchemy with multiple DDD Repositories?

我一直在尝试寻找一些示例,如何使用SQLAlchemy实现Repository模式。具体来说,是实现多个Repository。

在存在多个存储库的情况下,我认为最好通过维护单独的SQLAlchemy会话来实现每个存储库。然而,我一直遇到一个问题,即尝试将绑定到一个会话的对象实例移动到另一个会话。

首先,这样做有意义吗?每个存储库是否应该维护自己独立于其他存储库的工作单元,还是可以安全地使整个上下文共享相同的会话?

第二,如何最好地将实例从一个会话中分离并绑定到另一个会话?

第三,是否有任何以SQLAlchemy为出发点的坚实的DDD存储库示例?

最佳回答

我不熟悉DDD Repository模式,但以下是一个示例,显示如何将对象从一个会话移动到另一个会话:

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

metadata  = MetaData()
Base = declarative_base(metadata=metadata, name= Base )

class Model(Base):
    __tablename__ =  models 
    id = Column(Integer, primary_key=True)


engine1 = create_engine( sqlite:// )
metadata.create_all(engine1)
engine2 = create_engine( sqlite:// )
metadata.create_all(engine2)

session1 = sessionmaker(bind=engine1)()
session2 = sessionmaker(bind=engine2)()

# Setup an single object in the first repo.
obj = Model()
session1.add(obj)
session1.commit()
session1.expunge_all() 

# Move object from the first repo to the second.
obj = session1.query(Model).first()
assert session2.query(Model).count()==0
session1.delete(obj)
# You have to flush before expunging, otherwise it won t be deleted.
session1.flush()
session1.expunge(obj)
obj = session2.merge(obj)
# An optimistic way to bind two transactions is flushing before commiting.
session2.flush()
session1.commit()
session2.commit()
assert session1.query(Model).count()==0
assert session2.query(Model).count()==1
问题回答

暂无回答




相关问题
DDD - Returning entity in response to a service operation

I am new to domain driven development & have a simple question. If a service needs to generate some entity as a response to an operation then how should it be done? One of the ways is to inject ...

Domain Driven Design efforts in dynamic languages? [closed]

Are you aware of any DDD efforts in a dynamic language ? Practical resources on DDD tend to decrease quite dramatically when straying from enterprise-oriented solutions (a google search exluding C#, ....

Accessing domain objects in the view

If I don t want to expose the internal state of my Domain Objects, but I need to display them, I can think of three approaches. Which of these is the most "correct" (if any?). The "DTO/ViewModel ...

DDD screen cast question?

I wathced a screen cast on DDD by Greg Young the other day which spoke about persisting all state transitions of an object, instead of it s state when saved, then to load it "replay" all these ...

How to fluent-map this (using fluent nhibernate)?

I have two tables in my database "Styles" and "BannedStyles". They have a reference via the ItemNo. Now styles can be banned per store. So if style x is banned at store Y then its very possible that ...

热门标签