0

我以前使用过 SQLAlchemy,根据我的经验,我可以在 SQLAlchemy 中进行从类到表的声明性映射以及类之间的关系。

这是声明的示例:

class Item(Base):
     __tablename__ = 'item'

     id = Column(Integer, Sequence('item_seq'), primary_key=True)
     barcode = Column(String, unique=True)
     shortdesc = Column(String)
     desc   = Column(String)
     reg_date = Column(DateTime)
     registrar = Column(String)
     category = Column(String, ForeignKey('category.code'))
     supplier = Column(String, ForeignKey('supplier.code'))
     stock_on_hand = Column(Integer)
     cost = Column(Float)
     price = Column(Float)
     unit = Column(String, ForeignKey('unit.code'))

     receiving = relationship('Receiving', backref='item')
     adjustment = relationship('Adjustment', backref='item')
     sales = relationship('Sales', backref='sales')

     def __repr__(self):
        return "<Item('%s','%s','%s', '%s')>" % (self.barcode, self.shortdesc, self.stock_on_hand, self.unit)

class Supplier(Base):

     __tablename__ = 'supplier'

     code = Column(String, primary_key=True)
     name = Column(String)
     reg_date = Column(DateTime)
     registrar = Column(String)
     address_line_1 = Column(String)
     address_line_2 = Column(String)
     address_line_3 = Column(String)
     postcode = Column(String)
     city = Column(String)
     state = Column(String)
     country = Column(String)
     phone = Column(String)
     fax = Column(String)
     representative = Column(String)

     item = relationship('Item',backref='supplier')

    def __repr__(self):
    return "<Supplier('%s','%s','%s')>" % (self.code, self.name, self.representative)

Supplier与表具有一对多关系的地方Item,以及可以从这些类声明中创建关系。

我可以对 Hibernate 做同样的事情吗?如何?我在谷歌上下搜索,但我只发现在 Hibernate 中从表到类的逆向工程。

如果可以这样做,我们如何处理 Hibernate 中的关系?

4

1 回答 1

0

不是 100% 确定我正确理解了您的问题,但这里是:

最简单的是,它看起来像这样:

public class Supplier {
    @Identity
    @GeneratedValue
    private Long id; 
    //stuff
    @OneToMany(mappedBy="supplier")
    private List<Item> items;
    //more stuff
}

public class Item {
    @Identity
    @GeneratedValue
    private Long id; 
    //item stuff
    @ManyToOne
    private Supplier supplier;
    //more item stuff
}

which states that a supplier has a number of items, and an item has a supplier. The mappedBy property states that in the database, the Item-table will have a column supplier_id, which a foreign key to the Supplier-table

于 2013-03-16T12:30:12.600 回答