百思不得其解,请教

08-05-20 hiworld

举个例子

有学生Student和班级Team两个类:

public class Student { public class Team{

private Integer sno; // 学号

private String sname; // 姓名 private Integer tno; // 班级号

private String password; // 密码 private String academyName; // 院系名称

private Team team; // 班级 ......

...........

public Team getTeam() { .......

return team;

} seter和getter方法省略

public void setTeam(Team team) { ........

this.team = team;

} }

其他settr,getter省略

..........

}

映射多对一关联

Student.hbm.xml

...

<many-to-one name="team" column="TEAM_ID" class="com.gc.vo.Team"

cascade="save-update" />

...

可以插入,删除都没有问题.

但查询有个奇怪的问题:

下面测试类

public static void main(String[] args) {

try {

Session s=HibernateSessionFactory.getSession();

StudentDAOImpl sdao=new StudentDAOImpl();//此行在下面例子用到

Student stu=(Student)s.load(Student.class,1);

System.out.println("sname: " + stu.getSname());

System.out.println("tname: " +stu.getTeam().getTeamName());

} catch (Exception e) {}

}

可以输出:

sname: tom

tname: cs

但根据学号和密码来查询学生:把Student stu=(Student)s.load(Student.class,1);

改为 Student stu=(Student)sdao.queryStudent(1, "yes");

StudentDAOImpl.java如下

public class StudentDAOImpl implements StudentDao {

....

public Student queryStudent(Integer sno, String password) throws Exception {

Session session = getSession();

Transaction tx = null;

try {

tx = session.beginTransaction();

Student student = (Student) session.load(Student.class, sno);

tx.commit();

if (password.equals(student.getPassword())) {

return student;

} else {return null;}

} catch (HibernateException e) {

if (tx != null) {tx.rollback();}

throw e;

} finally {session.close();}

}

....

}

输出结果:

sname: tom

班级名称输不出:但只是可以输出班级号System.out.pirntln("Tno: " + stu.getTeam.getTno);

Tno: 2

hiworld
2008-05-28 14:00

自己踩一下