Hibernate學習實例:關聯表的樹狀結構設計

說明:

一、使用的Hibernate版本是hibernate-release-4.3.11.Final.

二、實例:一個公司有許多子公司

三、映射的時候,在同一個類中使用ManyToOne 和 OneToMany

四、本次只使用Annotation版本,其他版本可參考之前的博客

實體類:

Org.java:

package com.buaa.hibernate.homework;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity
public class Org {
	private int id;
	private String name;
	private Set<Org> children = new HashSet<Org>();
	private Org parent;
	
	public Org(String name){
		this.name = name;
	}
	
	@Id
	@GeneratedValue
	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;
	}
	@OneToMany(cascade={CascadeType.ALL},mappedBy="parent",fetch=FetchType.EAGER)
	public Set<Org> getChildren() {
		return children;
	}
	public void setChildren(Set<Org> children) {
		this.children = children;
	}
	@ManyToOne
	@JoinColumn(name="pid")
	public Org getParent() {
		return parent;
	}
	public void setParent(Org parent) {
		this.parent = parent;
	}
	
}
hibernate配置文件 :hibernate.cfg.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>

		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

		<!-- Assume test is the database name -->
		<property name="connection.url">jdbc:mysql://localhost/test</property>
		<property name="connection.username">root</property>
		<property name="connection.password">123456</property>

		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>

		<property name="format_sql">true</property>
		<property name="hbm2ddl.auto">create</property>

		<mapping class="com.buaa.hibernate.homework.Org" />

	</session-factory>
</hibernate-configuration>
Junit測試類:

OrgTest.java:

package com.buaa.hibernate.homework;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;


public class OrgTest {
	private SessionFactory factory;
	private Session session;
	
	@Before
	public void before(){
		Configuration configuration = new Configuration().configure();
		ServiceRegistry service = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
		 factory = configuration.buildSessionFactory(service);
		 session = factory.openSession();
	}
	
	//往數據庫中存儲數據
	@Test
	public void test(){
		Org o = new Org("company");
		Org o1 = new Org("company_1");
		Org o2 = new Org("company_2");
		Org o11 = new Org("company_1_1");
		Org o12 = new Org("company_1_2");
		o.getChildren().add(o1);
		o.getChildren().add(o2);
		o1.getChildren().add(o11);
		o1.getChildren().add(o12);
		o1.setParent(o);
		o2.setParent(o);
		o11.setParent(o1);
		o12.setParent(o1);
		
		session.beginTransaction();
		session.save(o);
		session.getTransaction().commit();
		
	}
	
	//從數據庫中讀取數據
	@Test
	public void loadTest(){
		test();
		
		session.beginTransaction();
		
		Org o = (Org)session.load(Org.class, 1);
		print(o,0);
		
		session.getTransaction().commit();
	}
	
	//用遞歸的方法,獲取所有的子類,並且縮進顯示
	private void print(Org o,int level) {
		String buffer = "";
		for(int i=0;i<level;i++){
			buffer += "----";
		}
		System.out.println(buffer + o.getName());
		for(Org child : o.getChildren()){
			print(child,level+1);
		}
	}

	
	@After
	public void after(){
		session.close();
		factory.close();
	}
}
數據庫的建表語句:

Hibernate: 
    alter table Org 
        drop 
        foreign key FK_n4sv1hojgjugxnfjsourei39b
Hibernate: 
    drop table if exists Org
Hibernate: 
    create table Org (
        id integer not null auto_increment,
        name varchar(255),
        pid integer,
        primary key (id)
    )
Hibernate: 
    alter table Org 
        add constraint FK_n4sv1hojgjugxnfjsourei39b 
        foreign key (pid) 
        references Org (id)

最後是從數據庫中讀取到的數據:

company
----company_2
----company_1
--------company_1_2
--------company_1_1





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章