Hibernate Class-to-Table映射关系

时间:2013-03-16 08:32:14

标签: java hibernate sqlalchemy

之前我曾与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)

SupplierItem之间存在一对多关系的表格,以及可以从这些类声明中创建关系。

我可以用Hibernate做同样的事吗?怎么样?我googled高低,但我只在Hibernate中找到了从一个表到另一个类的逆向工程。

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

1 个答案:

答案 0 :(得分: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
}

表示供应商有多个商品,而商品有供应商。 mappedBy属性声明在数据库中,Item - 表将有一个列supplier_id,它是Supplier - 表的外键