在这里以客户(Customer)与订单(Order)为例,订单为多的一方,客户为一的一方。
实体类创建
- 订单
public class Orders {
private Integer oid;
private Double price;
private String adress; // 收货地址
// 订单与客户关联
private Customer customer;// 描述订单属于某个客户
// 以下省略get与set方法
}
- 客户
public class Customer {
private Integer cid;
private String name;
// 描述客户有多个订单
private Set<Orders> orders = new HashSet<Orders>();
// 以下省略get与set方法
}
##Hbm映射文件编写
- Orders.hbm.xml
<class name="com.wang.domain.Orders">
<id name="oid" column="o_id">
<generator class="native"/>
</id>
<property name="price" column="o_price"/>
<property name="adress" column="o_adress"/>
<many-to-one name="customer" column="customer_id" class="com.wang.domain.Customer" cascade="save-update"/>
</class>
- Customer.hbm.xml
<class name="com.wang.domain.Customer">
<id name="cid" column="c_id"><generator class="native"/></id>
<property name="name" column="c_name"/>
<set name="orders" cascade="save-update">
<key column="customer_id"></key>
<one-to-many class="com.wang.domain.Orders" />
</set>
</class>
hibernate配置文件需要添加映射文件路径
<mapping resource="com/wang/domain/Customer.hbm.xml" />
<mapping resource="com/wang/domain/Orders.hbm.xml" />
测试保存
@Test
public void test1(){
Configuration cf = new Configuration().configure();
SessionFactory sf = cf.buildSessionFactory();
Session session = sf.openSession();
Transaction tsc = session.beginTransaction();
Customer c1 = new Customer();
c1.setName("Jar");
Orders o1 = new Orders();
o1.setPrice(100d);
o1.setAdress("huqi1");
Orders o2 = new Orders();
o2.setPrice(200d);
o2.setAdress("huqi2");
c1.getOrders().add(o1);
c1.getOrders().add(o2);
//因为设置了双向级联保存所以只需保存客户就好,否则客户与订单都要save保存
session.save(c1);
tsc.commit();
session.close();
}