本程式主要是參考金角大王部落格
做了乙個orm可增可查的外來鍵關聯查詢實驗
#-*- coding:utf-8 -*-
from sqlalchemy import integer, foreignkey, string, column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship,sessionmaker
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql:",
encoding='utf-8', echo=true,convert_unicode=true)#?charset=utf8才使orm真正能存中文資料
base = declarative_base()
class customer(base):
__tablename__ = 'customer'
id = column(integer, primary_key=true)
name = column(string(32))
__table_args__ =
billing_address_id = column(integer, foreignkey("address.id"))
shipping_address_id = column(integer, foreignkey("address.id"))
billing_address = relationship("address", foreign_keys=[billing_address_id])
shipping_address = relationship("address", foreign_keys=[shipping_address_id])
class address(base):
__tablename__ = 'address'
id = column(integer, primary_key=true)
street = column(string(64))
city = column(string(32))
state = column(string(32))
__table_args__ =
def __repr__(self):
return "" % (self.street, self.city, self.state)
base.metadata.create_all(engine) #建立表結構
session_class = sessionmaker(bind=engine) #建立與資料庫的會話session class ,注意,這裡返回給session的是個class,不是例項
session = session_class() #生成session例項
#-------------------增----------------------
# ad1=address(street="中山北路",city="閘北區",state="上海")
# ad2=address(street="南京路",city="黃浦區",state="上海")
# ad3=address(street="北京西路",city="靜安區",state="上海")
# ad4=address(street="嘉松中路",city="青浦區",state="上海")
# session.add_all([ad1,ad2,ad3,ad4]) #把要建立的資料物件新增到這個session裡, 一會統一建立
# c1=customer(name="jack",billing_address_id=1,shipping_address_id=1)
# c2=customer(name="cici",billing_address_id=2,shipping_address_id=3)
# c3=customer(name="bob",billing_address_id=4,shipping_address_id=4)
# session.add_all([c1,c2,c3])
#-------------------查----------------------
info=session.query(customer).filter(customer.name=="cici").first()
print(info.name,info.billing_address,info.shipping_address)
session.commit() #現此才統一提交,建立資料
Hibernate關聯查詢 一對多雙向關聯
dept實體類 public class dept public void setemps setemps private setemps new hashset public integer getdeptno public void setdeptno integer deptno public...
MyBatis 一對多雙向關聯查詢
一 為teacher實體增加相關屬性 為教師實體增加指導學生集合的屬性如下 1 privatelistsupstudents 指導學生 並為其增加setter和getter方法,這裡略過。為實現教師實體對映,應先建立對映器介面如下 1 2 3 4 5 package importcom.abc.do...
JPA單項一對多外來鍵關聯
一對多即乙個物件中包含又另外乙個物件的集合。user主表 table name user entity public class user public void setlistorder listlistorder id tablegenerator name pk primary table o...