分享
 
 
 

Hibernate一对多单向关系

王朝java/jsp·作者佚名  2006-05-02
窄屏简体版  字體: |||超大  

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对象持久化技术详解 孙卫琴

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有