1. 程式人生 > >Hibernate一對多單向關聯

Hibernate一對多單向關聯

Hibernate一對多單向關係
業務邏輯:

Teacher類和Student類,假定為一對多的關係,即一個教師有多個學生。

1. 資料庫schema
Teachers表:
create table TEACHERS
(
ID  NUMBER(10) not null,
TEACHERNAME VARCHAR2(15)
);

alter table TEACHERS
add constraint DERE primary key (ID)

Students表:
create table STUDENTS
(
ID NUMBER(10) not null,
STUDENTNAME VARCHAR2(15),
TEACHER_ID NUMBER(10)
);

alter table STUDENTS
add constraint RERE primary key (ID)
alter table STUDENTS
add constraint FFF foreign key (TEACHER_ID)
references TEACHERS (ID);

2. Teacher.Java和Student.java
Teacher.java

package mypack;
public class Teacher {
//教師id
private Long id;
//教師名稱
private String teacherName;
/**
   * 預設建構函式

   */

public Teacher() {

}
/**
   * 得到教師id
   * @return Long    教師id
   */

public Long getId() {
    return id;
}
/**
   * 設定教師id
   * @param id Long    教師id
   */
public void setId(Long id) {
    this.id = id;
}
/**
   * 得到教師名稱
   * @return String    教師名稱
   */
public String getTeacherName() {
    return teacherName;
}
/**
   * 設定教師名稱
   * @param teacherName String    教師名稱
   */
public void setTeacherName(String teacherName) {
    this.teacherName = teacherName;
}
/**
   * 建構函式
   * @param teacherName String
   */

public Teacher(String teacherName) {
    this.teacherName = teacherName;
}

Student.java
package mypack;
public class Student {
//學生id
private Long id;
//學生名稱
private String studentName;
//教師類
private Teacher teacher;
/**
   * 預設建構函式

   */

public Student() {

}
/**
   * 得到學生id

   * @return Long    學生id

   */

public Long getId() {

    return id;

}
/**
  * 設定學生id

   * @param id Long    學生id
   */

public void setId(Long id) {
    this.id = id;
}
/**
  * 得到學生名稱
   * @return String    學生名稱
   */

public String getStudentName() {
    return studentName;
}

/**
   * 設定學生名稱

   * @param studentName String    學生名稱

   */

public void setStudentName(String studentName) {

    this.studentName = studentName;
}

/**

   * 得到教師物件

   * @return Teacher    教師物件

   */

public Teacher getTeacher() {
    return teacher;
}

/**

   * 設定教師物件

   * @param teacher Teacher    教師物件

   */

public void setTeacher(Teacher teacher) {

    this.teacher = teacher;
}

/**

   * 建構函式

   * @param string String

   * @param teacher Teacher

   */

public Student(String studentName, Teacher teacher) {

    this.studentName = studentName;

    this.teacher = teacher;
}

3.   hibernate.properties
## Oracle

hibernate.dialect net.sf.hibernate.dialect.Oracle9Dialect

hibernate.dialect net.sf.hibernate.dialect.OracleDialect

hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver

hibernate.connection.username jbcm

hibernate.connection.passWord jbcm

hibernate.connection.url jdbc:oracle:thin:@localhost:1521:wsy


4.   Teacher.hbm.xml和Student.hbm.xml
Teacher.hbm.xml
<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping

PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping >


<class name="mypack.Teacher" table="teachers" >

    <id name="id" type="long" column="ID">

      <generator class="increment"/>

    </id>


    <property name="teacherName" type="string" >

        <column name="teacherName" length="15" />

    </property>

</class>

</hibernate-mapping>

Student.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping

PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping >

<class name="mypack.Student" table="students" >

    <id name="id" type="long" column="ID">

      <generator class="increment"/>

    </id>
    <property name="studentName" type="string" >
       <column name="studentName" length="15" />
    </property>

   <many-to-one

        name="teacher"

       column="teacher_id"

        class="mypack.Teacher"

        cascade="save-update"

       />

</class>
</hibernate-mapping>


5.   資料庫操作類
BusinessService.java

package mypack;


import net.sf.hibernate.*;

import net.sf.hibernate.cfg.Configuration;

import java.util.*;


public class BusinessService{

//session工廠類

public static SessionFactory sessionFactory;

//實始化session工廠

static{
     try{

       //建立配置類,新增Student類和Teacher類

       Configuration config = new Configuration();

       config.addClass(Student.class)

             .addClass(Teacher.class);

      //得到sessionFactory物件

      sessionFactory = config.buildSessionFactory();

    }catch(Exception e){e.printStackTrace();}
}


/**

   * 通過學生類,查詢教師類

   * @param student Student

   * @throws Exception

   * @return List

   */

public List findTeacherByStudent(Student student) throws Exception{

    Session session = sessionFactory.openSession();

    Transaction tx = null;

    try {

      tx = session.beginTransaction();


      List orders=(List)session.find("from Student as o where o.teacher.id="+student.getId());

      tx.commit();

      return orders;

    }catch (Exception e) {

       if (tx != null) {

        tx.rollback();
      }
      throw e;

    } finally {

      session.close();

    }

}

/**

   * 查詢指定id的學生類

   * @param student_id long

   * @throws Exception

   * @return Student

   */

public Student findStudent(long student_id) throws Exception{

    Session session = sessionFactory.openSession();

    Transaction tx = null;

    try {

      tx = session.beginTransaction();

      Student student=(Student)session.load(Student.class,new Long(student_id));

      tx.commit();

       return student;

    }catch (Exception e) {

      if (tx != null) {

        //發生錯誤,回滾

        tx.rollback();

      }
      throw e;

    } finally {

      //沒有錯誤,關閉session

      session.close();

    }

}


/**

   * 級連儲存Teacher物件和Student物件

   * @throws Exception

   */

public void saveTeacherAndStudentWithCascade() throws Exception{

    Session session = sessionFactory.openSession();

    Transaction tx = null;

    try {

      tx = session.beginTransaction();

      Teacher teacher=new Teacher("myTeacher");

      Student student1=new Student("student1",teacher);

      Student student2=new Student("student2",teacher);


      session.save(student1);

      session.save(student2);

      tx.commit();

    }catch (Exception e) {

      if (tx != null) {

         //發生錯誤,回滾

        tx.rollback();

      }

      e.printStackTrace();

    } finally {

      // 沒有錯誤,關閉session

      session.close();

    }

}


/**

   * 儲存教師和學生物件

   * @throws Exception

   */

public void saveTeacherAndStudent() throws Exception{

    Session session = sessionFactory.openSession();

    Transaction tx = null;

    try {

      tx = session.beginTransaction();


      Teacher teacher=new Teacher("teacher1");

      session.save(teacher);


      Student student1=new Student("student001",teacher);

      Student student2=new Student("student002",teacher);

      session.save(student1);

      session.save(student2);

      //提交事務

      tx.commit();

    }catch (Exception e) {

      if (tx != null) {

        //發生錯誤,回滾

        tx.rollback();

      }

       throw e;

    } finally {

      // 沒有錯誤,關閉session

      session.close();

    }

}
/**

   * 輸出學生物件集合

   * @param students List

   */

public void printStudents(List students){

      for (Iterator it = students.iterator(); it.hasNext();) {

         Student student=(Student)it.next();

         System.out.println("OrderNumber of "+student.getTeacher().getTeacherName()+ " :"+student.getStudentName());

      }

}


/**

   * 測試方法

   * @throws Exception

   */

public void test() throws Exception{

      saveTeacherAndStudent();

//      saveTeacherAndStudentWithCascade();

//      Student student=findStudent(1);

//      List students=findTeacherByStudent(student);

//      printStudents(students);

}


public static void main(String args[]) throws Exception {

    new BusinessService().test();

    sessionFactory.close();

}

}