日期:2014-05-19  浏览次数:20799 次

指点 使用hibernate时为什么会出现两条新增记录
public static void saveAll2(){
Session session=HibernateSessionFactory.getSession();

Grade grade=(Grade)session.get(Grade.class, 8);
Student stu=new Student();
stu.setSname("美美");
stu.setSex("女");
grade.getStudentId().add(stu);
//创建第一个课程对象
Course co=new Course();
co.setCname("JAVA");
co.setCdesc("OOP面向对象");
//创建第二个课程对象
Course co2=new Course();
co2.setCname("C#");
co2.setCdesc("面向对象");
//让学生选择两门课程
stu.getCourse().add(co);
stu.getCourse().add(co2);
co.getStudents().add(stu);
co2.getStudents().add(stu);

session.beginTransaction();
session.save(stu);
session.getTransaction().commit();
session.close();
}




Hibernate: 
  select
  grade0_.GID as GID2_0_,
  grade0_.GNAME as GNAME2_0_,
  grade0_.GDESC as GDESC2_0_ 
  from
  JBIT.GRADE grade0_ 
  where
  grade0_.GID=?
Hibernate: 
  select
  studentid0_.gid as gid1_,
  studentid0_.SID as SID1_,
  studentid0_.SID as SID0_0_,
  studentid0_.SNAME as SNAME0_0_,
  studentid0_.SEX as SEX0_0_,
  studentid0_.gid as gid0_0_ 
  from
  JBIT.STUDENT studentid0_ 
  where
  studentid0_.gid=?
Hibernate: 
  select
  hibernate_sequence.nextval 
  from
  dual
Hibernate: 
  select
  BANK_ID.nextval 
  from
  dual
Hibernate: 
  select
  BANK_ID.nextval 
  from
  dual
Hibernate: 
  insert 
  into
  JBIT.STUDENT
  (SNAME, SEX, gid, SID) 
  values
  (?, ?, ?, ?)
Hibernate: 
  insert 
  into
  JBIT.COURSE
  (CNAME, CDESC, CID) 
  values
  (?, ?, ?)
Hibernate: 
  insert 
  into
  JBIT.COURSE
  (CNAME, CDESC, CID) 
  values
  (?, ?, ?)
Hibernate: 
  update
  JBIT.STUDENT 
  set
  gid=? 
  where
  SID=?
Hibernate: 
  insert 
  into
  sc
  (sid, cid) 
  values
  (?, ?)
Hibernate: 
  insert 
  into
  sc
  (sid, cid) 
  values
  (?, ?)
Hibernate: 
  insert 
  into
  sc
  (cid, sid) 
  values
  (?, ?)
Hibernate: 
  insert 
  into
  sc
  (cid, sid) 
  values
  (?, ?)


------解决方案--------------------
我想大概是获取了两个transaction对象导致的,session.getTransaction(),
每获取一次它就保存一次、