1. 程式人生 > >Hibernate 超簡單的一對多和多對一查詢

Hibernate 超簡單的一對多和多對一查詢

這裡使用的Teacher類和Student類(假設一個Teacher對應多個學生,一個學生對應一個老師)

所需jar包


開始建表

1(表名 teacher)


2(表名 student)


主鍵都為自增長

建立實體類

Teacher類

package com.bright.po;

import java.util.Set;

public class Teacher {
	private Integer id;
	private String name;
	private Integer age;
	private Set<Student> students;
	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 Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Set<Student> getStudents() {
		return students;
	}
	public void setStudents(Set<Student> students) {
		this.students = students;
	}
	@Override
	public String toString() {
		return "Teacher [id=" + id + ", name=" + name + ", age=" + age
				+ ", students=" + students + "]";
	}
}

Student類

package com.bright.po;

public class Student {
	private Integer id;
	private String name;
	private Teacher teacher;
	
	public Student() {
		super();
	}
	public Student(String name, Teacher teacher) {
		super();
		this.name = name;
		this.teacher = teacher;
	}
	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 Teacher getTeacher() {
		return teacher;
	}
	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + "]";
	}
}

配置Teacher類的對映檔案

<?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 package="com.bright.po">
    <!-- 
        name:即實體類的全名
        table:對映到資料庫裡面的那個表的名稱
        catalog:資料庫的名稱
     -->
    <class name="Teacher" table="teacher" catalog="me">
        <!-- class下必須要有一個id的子元素 -->
        <!-- id是用於描述主鍵的 -->
        <id name="id" column="id">
            <!-- 主鍵生成策略 -->
            <generator class="native"></generator>
        </id>
        <!-- 
            使用property來描述屬性與欄位的對應關係
            如果length忽略不寫,且你的表是自動建立這種方案,那麼length的預設長度是255
        -->
        <property name="name" column="name" length="20"></property>
        <property name="age" column="age" length="20"></property>
        <!-- 一對多關聯對映配置(通過部門管理到員工)   
             Teacher對映關鍵點:  
               1.指定對映的集合屬性:students  
               2.集合屬性對應的集合表:student  
               3.集合表的外來鍵欄位:t_id 
               4.集合元素的型別-->  
        <set name = "students" table = "student">
        	<key column="t_id"></key>
        	<one-to-many class="Student"></one-to-many>
        </set>
    </class>
</hibernate-mapping>

配置Student類的對映檔案

<?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 package="com.bright.po">
    <!-- 
        name:即實體類的全名
        table:對映到資料庫裡面的那個表的名稱
        catalog:資料庫的名稱
     -->
    <class name="Student" table="student" catalog="me">
        <!-- class下必須要有一個id的子元素 -->
        <!-- id是用於描述主鍵的 -->
        <id name="id" column="id">
            <!-- 主鍵生成策略 -->
            <generator class="native"></generator>
        </id>
        <!-- 
            使用property來描述屬性與欄位的對應關係
            如果length忽略不寫,且你的表是自動建立這種方案,那麼length的預設長度是255
        -->
        <property name="name" column="name" length="20"></property>
         <!-- 一對多關聯對映配置(通過部門管理到員工)   
             Student對映關鍵點:  
               1.指定對映的屬性:teacher  
               2.集合表的外來鍵欄位:t_id 
               3.元素的型別:teacher-->  
        <many-to-one name="teacher" column="t_Id" class="Teacher"></many-to-one>
    </class>
</hibernate-mapping>

配置Hibrnate的配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 配置關於資料庫連線的四個項:driverClass  url username password -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///me</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <!-- 可以將向資料庫傳送的SQL語句顯示出來 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL語句 -->
        <property name="hibernate.format_sql">true</property>

        <!-- hibernate的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- 配置hibernate的對映檔案所在的位置 -->
        <mapping resource="com/bright/po/Teacher.hbm.xml" />
        <mapping resource="com/bright/po/Student.hbm.xml" />
    </session-factory>
</hibernate-configuration>

表中插入幾條資料

teacher表


student表


開始測試

首先寫個獲取Session的工具類

package com.bright.utils;

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

public class SessionUtils {
	public static Session getSession(){
		Configuration cfg = new Configuration().configure();
		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();
		session.beginTransaction();
		return session;
	}
	public static void closeSession(Session session){
		if(session!=null){
			session.getTransaction().commit();
			session.close();
		}
	}
}

具體測試

package com.bright.test;


import java.util.List;


import org.hibernate.Session;


import com.bright.po.Student;
import com.bright.po.Teacher;


import com.bright.utils.SessionUtils;


public class TestTeacher {
	public static void main(String[] args) {
		Session session = SessionUtils.getSession();
		List<Teacher> list = session.createQuery("from Teacher").list();
		for(Teacher t:list){
			System.out.println(t);
		}
		SessionUtils.closeSession(session);
	}
	
}

輸出結果

Hibernate: 
    select
        teacher0_.id as id1_1_,
        teacher0_.name as name2_1_,
        teacher0_.age as age3_1_ 
    from
        me.teacher teacher0_
Hibernate: 
    select
        students0_.t_id as t_id3_0_0_,
        students0_.id as id1_0_0_,
        students0_.id as id1_0_1_,
        students0_.name as name2_0_1_,
        students0_.t_Id as t_Id3_0_1_ 
    from
        me.student students0_ 
    where
        students0_.t_id=?
Teacher [id=1, name=白起, age=27, students=[Student [id=2, name=蘇烈], Student [id=3, name=劉邦], Student [id=1, name=亞瑟]]]
Hibernate: 
    select
        students0_.t_id as t_id3_0_0_,
        students0_.id as id1_0_0_,
        students0_.id as id1_0_1_,
        students0_.name as name2_0_1_,
        students0_.t_Id as t_Id3_0_1_ 
    from
        me.student students0_ 
    where
        students0_.t_id=?
Teacher [id=2, name=宮本武藏, age=25, students=[Student [id=6, name=蘭陵王], Student [id=4, name=孫悟空], Student [id=5, name=荊軻]]]
Hibernate: 
    select
        students0_.t_id as t_id3_0_0_,
        students0_.id as id1_0_0_,
        students0_.id as id1_0_1_,
        students0_.name as name2_0_1_,
        students0_.t_Id as t_Id3_0_1_ 
    from
        me.student students0_ 
    where
        students0_.t_id=?
Teacher [id=3, name=后羿, age=55, students=[Student [id=7, name=百里守約], Student [id=9, name=公孫離], Student [id=8, name=馬可波羅]]]

可以看出,查詢執行了多次,多次生成了sql語句,效率低,所以接下來採用了表的“迫切左外連線”。具體程式碼:

package com.bright.test;

import java.util.List;

import org.hibernate.Session;

import com.bright.po.Student;
import com.bright.po.Teacher;

import com.bright.utils.SessionUtils;

public class TestTeacher {
	public static void main(String[] args) {
		Session session = SessionUtils.getSession();
		List<Teacher> list = session.createQuery("select t from Teacher t left outer join fetch t.students").list();
		for(Teacher t:list){
			System.out.println(t);
		}
		SessionUtils.closeSession(session);
	}
	
}

查詢結果:

Hibernate: 
    select
        teacher0_.id as id1_1_0_,
        students1_.id as id1_0_1_,
        teacher0_.name as name2_1_0_,
        teacher0_.age as age3_1_0_,
        students1_.name as name2_0_1_,
        students1_.t_Id as t_Id3_0_1_,
        students1_.t_id as t_id3_0_0__,
        students1_.id as id1_0_0__ 
    from
        me.teacher teacher0_ 
    left outer join
        me.student students1_ 
            on teacher0_.id=students1_.t_id
Teacher [id=1, name=白起, age=27, students=[Student [id=3, name=劉邦], Student [id=1, name=亞瑟], Student [id=2, name=蘇烈]]]
Teacher [id=1, name=白起, age=27, students=[Student [id=3, name=劉邦], Student [id=1, name=亞瑟], Student [id=2, name=蘇烈]]]
Teacher [id=1, name=白起, age=27, students=[Student [id=3, name=劉邦], Student [id=1, name=亞瑟], Student [id=2, name=蘇烈]]]
Teacher [id=2, name=宮本武藏, age=25, students=[Student [id=4, name=孫悟空], Student [id=5, name=荊軻], Student [id=6, name=蘭陵王]]]
Teacher [id=2, name=宮本武藏, age=25, students=[Student [id=4, name=孫悟空], Student [id=5, name=荊軻], Student [id=6, name=蘭陵王]]]
Teacher [id=2, name=宮本武藏, age=25, students=[Student [id=4, name=孫悟空], Student [id=5, name=荊軻], Student [id=6, name=蘭陵王]]]
Teacher [id=3, name=后羿, age=55, students=[Student [id=8, name=馬可波羅], Student [id=7, name=百里守約], Student [id=9, name=公孫離]]]
Teacher [id=3, name=后羿, age=55, students=[Student [id=8, name=馬可波羅], Student [id=7, name=百里守約], Student [id=9, name=公孫離]]]
Teacher [id=3, name=后羿, age=55, students=[Student [id=8, name=馬可波羅], Student [id=7, name=百里守約], Student [id=9, name=公孫離]]]
這樣就好多了

結構圖