鎺ョ潃鍓嶉潰鐨勪緥瀛愯錛屾垜浠畾涔変簡book_table鍜宎uthor_table錛屾帴涓嬫潵錛?br />聽1聽class聽Book(object):
聽2聽聽聽聽聽def聽__init__(self,聽title):
聽3聽聽聽聽聽聽聽聽聽self.title聽=聽title
聽4聽聽聽聽聽def聽__repr__(self):
聽5聽聽聽聽聽聽聽聽聽return聽"<Book('%s')>"聽%聽self.title
聽6聽
聽7聽class聽Author(object):
聽8聽聽聽聽聽def聽__init__(self,聽name):
聽9聽聽聽聽聽聽聽聽聽self.name聽=聽name
10聽聽聽聽聽def聽__repr__(self):
11聽聽聽聽聽聽聽聽聽return聽"<Author('%s')>"聽%聽self.name
榪欓噷鎴戜滑瀹氫箟涓や釜綾伙紝緇ф壙鑷猳bject錛岀被浼糐avaBeans鎴栬匬OJO錛岃繖閲岀殑__init__鏂規硶鍜宊_repr__鏂規硶涓嶆槸蹇呴』鐨勶紝鍙槸涓轟簡鍒涘緩瀵硅薄鍜岃緭鍑哄璞″唴瀹規瘮杈冩柟渚褲傜劧鍚庡氨鍙互鐢⊿QLAlchemy鐨刴apper鍜宻essionmaker鏉ュ緩绔嬫槧灝勫叧緋誨茍澶勭悊鎸佷箙鍜屾煡璇㈢瓑鎿嶄綔錛?br />聽1聽from聽sqlalchemy.orm聽import聽mapper,sessionmaker
聽2聽
聽3聽mapper(Book,聽book_table)
聽4聽mapper(Author,聽author_table)
聽5聽
聽6聽Session聽=聽sessionmaker(bind=engine)
聽7聽session聽=聽Session()
聽8聽
聽9聽gia聽=聽Book(u'Groovy聽in聽Action')
10聽ag聽=聽Author(u'Andrew聽Glover')
11聽
12聽session.add(gia)
13聽session.add(ag)
14聽session.add_all([Book('Hibernate聽in聽Action'),聽Author('Gavin聽King')])
15聽s_gia聽=聽session.query(Book).filter_by(title=u'Groovy聽in聽Action').first()
16聽s_gia.title聽=u'Groovy聽in聽Action聽Updated'
17聽
18聽print聽"[DIRTY]",聽session.dirty
19
20聽session.commit() # or session.rollback()
濡傛灉浣犵敤榪嘓ibernate錛岄偅涔堣繖浜涗唬鐮佸浣犳潵璇達紝鐞嗚В璧鋒潵搴旇娌℃湁浠諱綍闅懼害銆?br />
鍋囧鎴戝憡璇変綘錛屾瘡嬈¢兘瑕佸儚榪欐牱鍏堝畾涔塗able(schema)錛屽啀瀹氫箟class錛岀劧鍚庣敤mapper寤虹珛瀵圭収錛屾槸涓嶆槸鏈夌偣閭e暐錛烻QLAlchemy鐨勫紑鍙戣呬滑涔熸剰璇嗗埌榪欎竴鐐癸紝鎵浠ヤ粠0.5寮濮嬶紝SQLAlchemy鍙互閫氳繃sqlalchemy.ext.declarative鏀寔鎴戜滑瀹炵幇鏇寸揣鍑戠殑model/schema瀹氫箟錛?br />聽1聽from聽sqlalchemy.schema聽import聽Table,聽Column,聽ForeignKey,聽Sequence
聽2聽from聽sqlalchemy.types聽import聽*
聽3聽from聽sqlalchemy.orm聽import聽relation
聽4聽from聽sqlalchemy.ext.declarative聽import聽declarative_base
聽5聽
聽6聽Base聽=聽declarative_base()
聽7聽metadata聽=聽Base.metadata
聽8聽
聽9聽bookauthor_table聽=聽Table('bookauthor',聽metadata,
10聽聽聽聽聽Column('book_id',聽Integer,聽ForeignKey('book.id'),聽nullable=False),
11聽聽聽聽聽Column('author_id',聽Integer,聽ForeignKey('author.id'),聽nullable=False),
12聽)
13聽
14聽class聽Book(Base):
15聽聽聽聽聽__tablename__聽=聽'book'
16聽聽聽聽聽id聽=聽Column(Integer,聽Sequence('seq_pk'),聽primary_key=True)
17聽聽聽聽聽title聽=聽Column(Unicode(255),聽nullable=False)
18聽聽聽聽聽authors聽=聽relation('Author',聽secondary=bookauthor_table)
19聽
20聽
21聽class聽Author(Base):
22聽聽聽聽聽__tablename__聽=聽'author'
23聽聽聽聽聽id聽=聽Column(Integer,聽Sequence('seq_pk'),聽primary_key=True)
24聽聽聽聽聽name聽=聽Column(Unicode(255),聽nullable=False)
25聽聽聽聽聽books聽=聽relation('Book',聽secondary=bookauthor_table)
榪欓噷鎴戜滑鐢ㄥ埌浜唌any-to-many鍏崇郴錛屽叾浠栫殑甯歌鐢ㄦ硶榪樺寘鎷琺any-to-one銆乷ne-to-many銆丣OIN銆佸瓙鏌ヨ銆丒XISTS銆丩azy/Eager Load銆丆ascade (all/delete/delete-orphan)絳夌瓑錛屽ぇ瀹跺彲浠ユ牴鎹渶瑕佹煡闃呭畼鏂規枃妗c?br />

]]>