1. 程式人生 > >Hibernate處理資料關係

Hibernate處理資料關係

Hibernate自我關聯對映

例如在設計選單的過程中,往往會將一個項抽象成為一個node物件,一個node物件可能擁有一個父node物件和多個子node物件。這樣從巨集觀來看,就是典型的自我關聯對映。

實現過程

- Node.java

package com.java1234.hibernate.model;

import java.util.Set;

public class Node {

	private int id;
	private String name;
	
	//1個父節點
	private Node parent;
	
	//多個子節點
	private Set<Node> childNodes;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		parent = parent;
	}

	public Set<Node> getChildNodes() {
		return childNodes;
	}

	public void setChildNodes(Set<Node> childNodes) {
		this.childNodes = childNodes;
	}
	
}

- node.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="com.java1234.hibernate.model.Node" table="tb_node">
    		<id name="id" column="nodeId" type="int">
    			<generator class="native"/>
    		</id>
    		<property name="name" column="nodeName"/>
    		
    		<!-- 1:n,一個父節點對應多個子節點。parentId:nodeId=1:n -->
    		<many-to-one name="parent" column="parentId" cascade="save-update" class="com.java1234.hibernate.model.Node"/>
    		
    		<!-- n:1,nodeId:childId=1:n -->
    		<set name="childNodes"  cascade="save-update">
    			<key column="childId"/>
    			<one-to-many class="com.java1234.hibernate.model.Node"/>
    		</set>
    	
    	</class>
    
    </hibernate-mapping>

生成的表結構

此過程中所執行的SQL語句

Hibernate: create table tb_node (nodeId integer not null auto_increment, nodeName varchar(255), parentId integer, childId integer, primary key (nodeId))
Hibernate: alter table tb_node add constraint FK_3aq8anhuwxcseocmsxmh4d0af foreign key (parentId) references tb_node (nodeId)
Hibernate: alter table tb_node add constraint FK_wj3wh29tcgwbqcxsg5tr559k foreign key (childId) references tb_node (nodeId)