どうすれば効果的に複数のDDDリポジトリとSQLAlchemyのを使用していますか?

StackOverflow https://stackoverflow.com/questions/2276523

質問

私はSQLAlchemyの持つリポジトリパターンを実装する方法のいくつかの例を見つけることを試みてきました。具体的には、複数のリポジトリを実現する。

複数のリポジトリの場合、私は、各リポジトリは最高別個SQLAlchemyのセッションを維持することによって実現されるであろうと考えています。しかし、私は別のセッションに1つのセッションにバインドされたオブジェクトのインスタンスを移動しようとしている問題に実行されている。

まず、これは何をする意味を成していますか?各リポジトリは独自のUOWが、他のリポジトリから分離したり、全体のコンテキストを共有し、同じセッションを持っていることは安全とみなされるべきで維持するべきでしょうか?

第二に、1セッションからインスタンスを切り離し、別にバインドするための最良の方法は何ですか?

第三に、心の中でSQLAlchemyのと書かれた任意の固体DDDリポジトリの例があるのですか?

役に立ちましたか?

解決

Iは、DDDリポジトリパターンに慣れていないんだけど、下記の別の1つのセッションからオブジェクトを移動する様子を示すexmapleある

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top