一 配置檔案
<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置檔案的DTD資訊 -->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置檔案的根元素 -->
<hibernate-configuration>
<session-factory>
<!-- 指定連接配接資料庫所用的驅動 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 指定連接配接資料庫的url,其中hibernate是本應用連接配接的資料庫名 -->
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<!-- 指定連接配接資料庫的使用者名 -->
<property name="connection.username">root</property>
<!-- 指定連接配接資料庫的密碼 -->
<property name="connection.password">32147</property>
<!-- 指定連接配接池裡最大連接配接數 -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- 指定連接配接池裡最小連接配接數 -->
<property name="hibernate.c3p0.min_size">1</property>
<!-- 指定連接配接池裡連接配接的逾時時長 -->
<property name="hibernate.c3p0.timeout">5000</property>
<!-- 指定連接配接池裡最大緩存多少個Statement對象 -->
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<!-- 指定資料庫方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 根據需要自動建立資料庫 -->
<property name="hbm2ddl.auto">update</property>
<!-- 顯示Hibernate持久化操作所生成的SQL -->
<property name="show_sql">true</property>
<!-- 将SQL腳本進行格式化後再輸出 -->
<property name="hibernate.format_sql">true</property>
<!-- 羅列所有持久化類的類名 -->
<mapping class="org.crazyit.app.domain.Enrolment"/>
<mapping class="org.crazyit.app.domain.Student"/>
<mapping class="org.crazyit.app.domain.Course"/>
</session-factory>
</hibernate-configuration>
二 PO
Student
package org.crazyit.app.domain;
import java.util.*;
import javax.persistence.*;
@Entity
@Table(name="student_inf")
public class Student
{
// 代表學生學号的成員變量,将作為辨別屬性
@Id @Column(name="student_id")
private Integer studentNumber;
// 代表學生姓名的成員變量
private String name;
// 該學生的所有選課記錄對應的關聯實體
@OneToMany(targetEntity=Enrolment.class
, mappedBy="student" , cascade=CascadeType.REMOVE)
private Set<Enrolment> enrolments
= new HashSet<>();
// 無參數的構造器
public Student()
{
}
// 初始化全部成員變量的構造器
public Student(Integer studentNumber , String name)
{
this.studentNumber = studentNumber;
this.name = name;
}
// studentNumber的setter和getter方法
public void setStudentNumber(Integer studentNumber)
{
this.studentNumber = studentNumber;
}
public Integer getStudentNumber()
{
return this.studentNumber;
}
// name的setter和getter方法
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
// enrolments的setter和getter方法
public void setEnrolments(Set<Enrolment> enrolments)
{
this.enrolments = enrolments;
}
public Set<Enrolment> getEnrolments()
{
return this.enrolments;
}
}
Enrolment
package org.crazyit.app.domain;
import javax.persistence.*;
@Entity
@Table(name = "enrolment_inf")
public class Enrolment
{
// 定義辨別屬性
@Id
@Column(name = "enrolment_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer enrolmentId;
// 定義選課記錄所屬的學年
private int year;
// 定義選課記錄所屬的學期
private int semester;
// 定義選課記錄關聯的學生實體
@ManyToOne(targetEntity = Student.class)
@JoinColumn(name = "student_id")
private Student student;
// 定義選課記錄關聯的課程實體
@ManyToOne(targetEntity = Course.class)
@JoinColumn(name = "course_code")
private Course course;
// enrolmentId的setter和getter方法
public void setEnrolmentId(Integer enrolmentId) {
this.enrolmentId = enrolmentId;
}
public Integer getEnrolmentId() {
return this.enrolmentId;
}
// year的setter和getter方法
public void setYear(int year) {
this.year = year;
}
public int getYear() {
return this.year;
}
// semester的setter和getter方法
public void setSemester(int semester) {
this.semester = semester;
}
public int getSemester() {
return this.semester;
}
// student的setter和getter方法
public void setStudent(Student student) {
this.student = student;
}
public Student getStudent() {
return this.student;
}
// course的setter和getter方法
public void setCourse(Course course) {
this.course = course;
}
public Course getCourse() {
return this.course;
}
}
Course
package org.crazyit.app.domain;
import javax.persistence.*;
@Entity
@Table(name="course_inf")
public class Course
{
// 代表課程編号的成員變量,将作為辨別屬性
@Id @Column(name="course_code")
private String courseCode;
// 代表課程名成員變量
private String name;
// 無參數的構造器
public Course()
{
}
// 初始化全部成員變量的構造器
public Course(String courseCode , String name)
{
this.courseCode = courseCode;
this.name = name;
}
// courseCode的setter和getter方法
public void setCourseCode(String courseCode)
{
this.courseCode = courseCode;
}
public String getCourseCode()
{
return this.courseCode;
}
// name的setter和getter方法
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
}
三 VO
package org.crazyit.app.vo;
public class StudentCourse
{
private String stuName;
private String courseName;
// stuName的setter和getter方法
public void setStuName(String stuName)
{
this.stuName = stuName;
}
public String getStuName()
{
return this.stuName;
}
// courseName的setter和getter方法
public void setCourseName(String courseName)
{
this.courseName = courseName;
}
public String getCourseName()
{
return this.courseName;
}
}
四 測試
1 工具類
package lee;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;
public class HibernateUtil
{
public static final SessionFactory sessionFactory;
static
{
try
{
// 使用預設的hibernate.cfg.xml配置檔案建立Configuration執行個體
Configuration cfg = new Configuration()
.configure();
// 以Configuration執行個體來建立SessionFactory執行個體
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
// ThreadLocal可以隔離多個線程的資料共享,是以不再需要對線程同步
public static final ThreadLocal<Session> session
= new ThreadLocal<Session>();
public static Session currentSession()
throws HibernateException
{
Session s = session.get();
// 如果該線程還沒有Session,則建立一個新的Session
if (s == null)
{
s = sessionFactory.openSession();
// 将獲得的Session變量存儲在ThreadLocal變量session裡
session.set(s);
}
return s;
}
public static void closeSession()
throws HibernateException
{
Session s = session.get();
if (s != null)
s.close();
session.set(null);
}
}
2 測試類
package lee;
import org.hibernate.*;
import org.hibernate.transform.*;
import java.util.*;
import org.crazyit.app.domain.*;
public class NamedSQLTest {
public static void main(String[] args) {
NamedSQLTest test = new NamedSQLTest();
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
test.simpleQuery();
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
test.query();
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
test.callProcedure();
HibernateUtil.sessionFactory.close();
}
// 執行簡單的命名SQL查詢
private void simpleQuery() {
// 打開Session和事務
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
// 調用命名查詢,直接傳回結果
List list = session.getNamedQuery("simpleQuery").list();
tx.commit();
HibernateUtil.closeSession();
// 周遊結果集
for (Object ele : list) {
// 每個集合元素是Student對象
Student s = (Student) ele;
System.out.println(s.getName() + "\t");
}
}
// 執行命名SQL查詢
private void query() {
// 打開Session和事務
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
// 調用命名查詢,直接傳回結果
List list = session.getNamedQuery("queryTest").setInteger("targetYear", 2005).list();
tx.commit();
HibernateUtil.closeSession();
// 周遊結果集
for (Object ele : list) {
// 每個集合元素是Student、Enrolment
// 和stuName三個元素的數組
Object[] objs = (Object[]) ele;
Student s = (Student) objs[0];
Enrolment e = (Enrolment) objs[1];
Course c = (Course) objs[2];
String stuName = (String) objs[3];
System.out.println(s.getName() + "\t" + e.getYear() + "\t" + e.getSemester() + "\t="
+ e.getCourse().getName() + "=\t" + stuName);
}
}
// 調用存儲過程
private void callProcedure() {
// 打開Session和事務
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
// 調用命名查詢,直接傳回結果
List list = session.getNamedQuery("callProcedure").list();
tx.commit();
HibernateUtil.closeSession();
// 周遊結果集
for (Object ele : list) {
// 每個集合元素是Student對象
Student s = (Student) ele;
System.out.println(s.getName());
}
}
}
四 資料腳本
drop database if exists hibernate;
create database hibernate;
use hibernate;
CREATE TABLE course_inf (
course_code varchar(255) NOT NULL,
name varchar(255) default NULL,
PRIMARY KEY (course_code)
);
INSERT INTO course_inf VALUES
('001','瘋狂Java講義'),
('002','輕量級Java EE企業應用實戰'),
('003','瘋狂Android講義');
CREATE TABLE student_inf (
student_id int NOT NULL,
name varchar(255) NOT NULL,
PRIMARY KEY (student_id)
);
INSERT INTO student_inf VALUES
(20050231,'孫悟空'),
(20050232,'豬八戒'),
(20050233,'牛魔王');
CREATE TABLE enrolment_inf (
enrolment_id int(11) NOT NULL auto_increment,
semester int(11) NOT NULL,
year int(11) NOT NULL,
student_id int default NULL,
course_code varchar(255) default NULL,
PRIMARY KEY (enrolment_id),
KEY FKEB4882C47EDE09EE (course_code),
KEY FKEB4882C4109881D8 (student_id),
FOREIGN KEY (student_id) REFERENCES student_inf (student_id),
FOREIGN KEY (course_code) REFERENCES course_inf (course_code)
);
INSERT INTO enrolment_inf VALUES
(1,3,2005,20050232,'001'),
(2,2,2005,20050232,'003'),
(3,2,2005,20050233,'002'),
(4,3,2005,20050233,'003'),
(5,1,2005,20050231,'002');
-- 建立一個簡單的存儲過程
create procedure select_all_student()
select *
from student_inf;
五 測試
Hibernate:
select
s.student_id ,
s.name
from
student_inf s
孫悟空
豬八戒
牛魔王
++++++++++++++++++++++++++++++++++++++++++++++++++++++
Hibernate:
select
s.*,
e.*,
c.*
from
student_inf s,
enrolment_inf e,
course_inf c
where
s.student_id = e.student_id
and e.course_code = c.course_code
and e.year=?
豬八戒 2005 3 =瘋狂Java講義= 豬八戒
豬八戒 2005 2 =瘋狂Android講義= 豬八戒
牛魔王 2005 2 =輕量級Java EE企業應用實戰= 牛魔王
牛魔王 2005 3 =瘋狂Android講義= 牛魔王
孫悟空 2005 1 =輕量級Java EE企業應用實戰= 孫悟空
++++++++++++++++++++++++++++++++++++++++++++++++++++++
Hibernate:
{call select_all_student()}
孫悟空
豬八戒
牛魔王