在1对n情况下,保存时怎么就保存一条数据,
如,Classes 和Students这种情况,只保存了Students中的最后一条数据,怎么同时保存集合中所有的Students对象数据?
Configuration cfg = new Configuration();// HibernateSessionFactory.getConfiguration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();

Transaction tx = session.beginTransaction();
Classes cl = new Classes();
cl.setClassdesc("高级班");
cl.setClassname("3班");
cl.setClasstype("测试班");
Students s = new Students();
 Set<Students> stu_Set=new HashSet<Students>();
for (int x = 0; x <= 5; x++) {
s.setStuName("v"+x);
s.setStuAge(x);
s.setStuSex("男"+x);
s.setClassid(cl);
stu_Set.add(s);

}
    
      
cl.setStudents(stu_Set);

try { session.saveOrUpdate(cl);
tx.commit();
session.flush();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}

解决方案 »

  1.   

    <class name="Father"
        table="Father"
        dynamic-update="false">
      <id  name="id" column="uuid" type="string" >
           <generator class="uuid.hex"/>
      </id>ww
      <set
          name="childList"
          inverse="true"
          lazy="false"
          order-by="name asc"
          cascade="all">
          <key column="father_id"/>
          <one-to-many class="Child"/>
        </set>
    </class>
    <class name="Child"
        table="Child"
        dynamic-update="false">
      <id  name="id" column="uuid" type="string" >
           <generator class="uuid.hex"/>
      </id>
      <many-to-one name="father" class="Father" column="father_id" not-null="true" outer-join="false"/>
    </class>
      

  2.   

    Class一的一段配置:
    <hibernate-mapping>
    <class name="com.yuli.model.Class" table="class">
    <id name="id">
    <generator class="native" />
    </id>
    <property name="name" />
    <set name="students">
    <key column="classid" />
    <one-to-many class="com.yuli.model.Student" />
    </set>
    </class>
    </hibernate-mapping>Student多的一段的配置:
    <hibernate-mapping>
    <class name="com.yuli.model.Student" table="student">
    <id name="id">
    <generator class="native"/>
    </id>
    <property name="name"/>
    </class>
    </hibernate-mapping>
      

  3.   

    谢谢各位,是红色的地方出问题了,网上的代码不可靠。Set <Students> stu_Set=new HashSet <Students>(); 
    for (int x = 0; x <= 5; x++) { 
    Students s = new Students(); 
    s.setStuName("v"+x); 
    s.setStuAge(x); 
    s.setStuSex("男"+x); 
    s.setClassid(cl); 
    stu_Set.add(s); }