网站首页
JSP空间
动态资讯
开源项目
技术文档
资源下载
J2EE资源
客户论坛
在线支付
 
  技术文档>>JAVA>>高级技术>>设计模式>查看文档  
  hibernate一对多单向关系     
  文章作者:未知  文章来源:中国IT实验室  
  查看:99次  录入:管理员--2007-11-20  
 

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.javastudent.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.xmlstudent.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      

 
 
上一篇: 谨慎使用类变量及正确使用单例模式    下一篇: 用java annotations管理对象生命周期
  相关文档
设计模式:用java动态代理实现aop 11-20
利用observer模式解决组件间通信问题 11-20
java模式之单例模式 11-20
深入浅出java设计模式之备忘录模式 11-20
一个简单的 thread 缓冲池的实现 11-20
深入浅出java设计模式之迭代器模式(图) 11-20
可扩展的java应用程序开发模式 11-20
备忘录模式(memento pattern) 11-20
无需调优的内存优化 11-20
教程:适配器模式(adapter pattern)组图 11-20
java设计模式之state(对应每种状态的行为) 11-20
框架不是框框—应用框架的基本思想 11-20
java设计模式之 decorator(装饰) 11-20
把业务流程从操作中剥离出来 11-20
Java模式开发之责任链模式(下) 03-14
/<麈E饰twrlZ)麖j媾k5j`醣m狷︿= %w猲q*涴7X廝I!#"佀栏枩/{w頕W?+f唅葙b]` 6T>趴纍Avt\Dk栜类焰*Q鸧5饢%佣q_Wgm飯珙U{