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();

}

}

目录结构示意:

Classes

                  Hibernate.property

       /mypack

                  Teacher.java

                            Student.java

                  BusinessService.java

                  Teacher.hbm.xml

                            Student.hbm.xml      

参考资料:精通Hibernate:Java对象持久化技术详解 孙卫琴

posted @ 2010-01-20 10:01  依然神思者  阅读(262)  评论(0编辑  收藏  举报