同样以商品和厂商为例,商品对厂商为多对1,则反过来,厂商对商品为1对多关系
public class Product { private Integer id; private String name; private double price; private Factory factory; public Product(){} public Product(Integer id){ this.id=id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Factory getFactory() { return factory; } public void setFactory(Factory factory) { this.factory = factory; } }
public class TestApplication7 { public static void main(String[] args) { Configuration configuration=new Configuration().configure(); SessionFactory sessionFactory=configuration.buildSessionFactory(); Session session=sessionFactory.openSession(); Transaction transaction=session.beginTransaction(); Integer(3)); System.out.println(product.getName()+"===="+product.getFactory().getFactoryname()); transaction.commit();*/ Factory factory=(Factory)session.get(Factory.class, new Integer(1)); Set<Product>products =factory.getProducts(); Iterator<Product> iterator=products.iterator(); while(iterator.hasNext()){ Product product=iterator.next(); System.out.println(product.getName()); } session.close(); }
<hibernate-mapping> <!-- 每一个class类对应一个持久化对象 --> <class name="model.Factory" table="mw_factory"> <id name="id"> <!-- 主键的生成策略 --> <generator class="identity"></generator> </id> <property name="Factoryname" type="string" length="45"> <column name="factoryName"></column> </property> <set name="products" inverse="true"> <key column="factoryid"></key> <one-to-many class="model.Product"/> </set> </class> </hibernate-mapping>
public class Factory { private int id; private String Factoryname; private Set<Product> products; public Factory(){} public Factory(Integer id){ this.id=this.id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFactoryname() { return Factoryname; } public void setFactoryname(String factoryname) { Factoryname = factoryname; } public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } }
<hibernate-mapping> <!-- 每一个class类对应一个持久化对象 --> <class name="model.Product" table="mw_product"> <id name="id"> <!-- 主键的生成策略 --> <generator class="identity"></generator> </id> <property name="name" type="string" length="45"> <column name="name"></column> </property> <property name="price" type="double"> <column name="price"></column> </property> <many-to-one name="factory" class="model.Factory" cascade="all"> <column name="factoryid"></column> </many-to-one> </class> </hibernate-mapping>