Hibernate,多对多的关联关系

数据对象之间的3种关联关系: 一对一一对多多对多
以商品(Item)和订单(Order)为例,这是个典型的多对多的案例。
因为,每个订单可以包含多种不同的商品,每种商品也可以拥有多个不同的订单。
多对多的关系,实际上完全可以拆分为两个一对多的关系(通常就这么用,效率高)
为了实现多对多的关系,还要为它们增加一个关系表(relations),用于保存其关系。
mysql> desc items;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(4)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

mysql> desc orders;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(4)       | NO   | PRI | NULL    | auto_increment |
| money | double(10,2) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

mysql> desc relations;
+----------+--------+------+-----+---------+-------+
| Field    | Type   | Null | Key | Default | Extra |
+----------+--------+------+-----+---------+-------+
| item_id  | int(4) | NO   | PRI | 0       |       |
| order_id | int(4) | NO   | PRI | 0       |       |
+----------+--------+------+-----+---------+-------+
Item.hbm.xml
<hibernate-mapping>
	<class name="PO.Item" table="items" catalog="test">
		<id name="id" type="int">
			<column name="id" />
			<generator class="identity" />
		</id>
		<property name="name" type="string">
			<column name="name" length="32" />
		</property>
		<!--映射Items与Orders的多对多的关联 -->
		<set name="orders" table="relations" cascade="all" inverse="true">
			<key column="item_id" />
			<many-to-many class="PO.Order" column="order_id" />
		</set>
	</class>
</hibernate-mapping>
Order.hbm.xml
<hibernate-mapping>
	<class name="PO.Order" table="orders">
		<id name="id" type="int">
			<column name="id" />
			<generator class="identity" />
		</id>
		<property name="money" type="double">
			<column name="money" />
		</property>
		<!--映射Orders与Items的多对多的关联 -->
		<set name="items" table="relations" cascade="all">
			<key column="order_id" />
			<many-to-many class="PO.Item" column="item_id" />
		</set>
	</class>
</hibernate-mapping>
Item.java
package PO;

import java.util.HashSet;
import java.util.Set;

public class Item implements java.io.Serializable {
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private Set<Order> orders = new HashSet<Order>();

	public Item() {
	}

	public Item(String name) {
		this.name = name;
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<Order> getOrders() {
		return orders;
	}

	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}
}
Order.java
package PO;

import java.util.HashSet;
import java.util.Set;

public class Order implements java.io.Serializable {
	private static final long serialVersionUID = 1L;
	private Integer id;
	private Double money;
	private Set<Item> items = new HashSet<Item>();

	public Order() {
	}

	public Order(Double money) {
		this.setMoney(money);
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Double getMoney() {
		return money;
	}

	public void setMoney(Double money) {
		this.money = money;
	}

	public Set<Item> getItems() {
		return items;
	}

	public void setItems(Set<Item> items) {
		this.items = items;
	}
}
test.java
package test;

import java.io.File;
import java.util.HashSet;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import PO.Item;
import PO.Order;

public class test {
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception {
		File file = new File("src/hibernate.cfg.xml");
		System.out.println("file path:" + file.getAbsolutePath());
		Configuration cfg = new Configuration().configure(file);
		SessionFactory sf = cfg.buildSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();

		Item item1 = new Item("item1");
		Integer id1 = (Integer) session.save(item1);
		System.out.println("save(item1) id:" + id1);
		Item item2 = new Item("item2");
		Integer id2 = (Integer) session.save(item2);
		System.out.println("save(item2) id:" + id2);

		Order order1 = new Order(1.1);
		// PO对象之间相互设置关联关系
		HashSet<Item> items1 = new HashSet<Item>();
		items1.add(item1);
		order1.setItems(items1);
		item1.getOrders().add(order1);
		Integer oid1 = (Integer) session.save(order1);
		System.out.println("save(order1) id:" + oid1);

		Order order2 = new Order(2.2);
		// PO对象之间相互设置关联关系
		HashSet<Item> items2 = new HashSet<Item>();
		items2.add(item2);
		order2.setItems(items2);
		item2.getOrders().add(order2);
		Integer oid2 = (Integer) session.save(order2);
		System.out.println("save(order2) id:" + oid2);

		Order order3 = new Order(3.3);
		// PO对象之间相互设置关联关系
		HashSet<Item> items3 = new HashSet<Item>();
		items3.add(item1);
		items3.add(item2);
		order3.setItems(items3);
		item1.getOrders().add(order3);
		item2.getOrders().add(order3);
		Integer oid3 = (Integer) session.save(order3);
		System.out.println("save(order3) id:" + oid3);

		Item new_item = (Item) session.get(Item.class, id1);
		if (new_item != null) {
			System.out.println("item id:" + new_item.getId() + ",name:"
					+ new_item.getName());
			for (Order tmp_order : new_item.getOrders()) {
				System.out.println("id:" + tmp_order.getId() + ",money:"
						+ tmp_order.getMoney());
			}
		}
		Order new_order = (Order) session.get(Order.class, oid3);
		if (new_order != null) {
			System.out.println("order id:" + new_order.getId() + ",money:"
					+ new_order.getMoney());
			for (Item tmp_item : new_order.getItems()) {
				System.out.println("id:" + tmp_item.getId() + ",name:"
						+ tmp_item.getName());
			}
		}

		// session.delete(item1);
		// session.delete(item2);
		// session.delete(order1);
		// session.delete(order2);
		// session.delete(order3);
		tx.commit();
		session.close();
		System.out.println("done.");
	}
}






你可能感兴趣的:(Hibernate,多对多的关联关系)