hibernate中many-to-one实例一

 

可以发现,添加一个教师的同时指定一个学生,这种方式相当糟糕,合理的方式应该是在添加学生的时候指定教师。即在学生类里指

定教师对象,配置文件里配置成many-to-one。

单纯只使用many-to-one:
在Student类里加入Teacher teacher属性。
注释掉teacher.hbm.xml里的<set ...></set>内容
在student.hbm.xml里入many-to-one属性:

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.sjtu.xw.pojo2"> <class name="Student" table="student"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="stuName" column="studentName" length="30" /> <many-to-one name="teacher" column="teacherId" class="Teacher" fetch="join" lazy="false" /> <!-- 这里的column="teacherId"是指明了自身(student表)表里的teacherId属性,指向teacher表的外键 --> </class> </hibernate-mapping> 

做完上述工作即可进行测试了:

Test2.java

package com.sjtu.xw.test; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.sjtu.xw.pojo2.Student; import com.sjtu.xw.pojo2.Teacher; import com.sjtu.xw.util.HibernateUtil; public class Test2 { public static void main(String[] args) { Test2 test = new Test2(); // test.addStudent();//通过 //test.addTeacher();//通过 test.test(); } public void addStudent() { Teacher teacher = new Teacher(); teacher.setId(1); Student student = new Student(); student.setStuName("student8"); student.setTeacher(teacher); SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); session.save(student); tx.commit(); session.close(); sf.close(); } public void addTeacher() { Teacher teacher = new Teacher(); teacher.setTeaName("Teacher5"); SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); session.save(teacher); tx.commit(); session.close(); sf.close(); } public void test() { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); List list = session.createQuery("from Student s where s.id=1").list(); Student s = (Student) list.get(0);//找student的id为1的学生,并获取老师的信息。 // System.out.println(s); System.out.println(s.getTeacher()); System.out.println(s.getTeacher().getTeaName()); tx.commit(); session.close(); sf.close(); } } 

 

 

转载于:https://www.cnblogs.com/xwdreamer/archive/2010/12/01/2297065.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值