HIbernate 一对多关系只能保存一个

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [hibernate.student1#0]

这是报错的信息


这是测试类

public class GSTest {


private SessionFactory sessionFactory;

  private Session session;

  private Transaction transaction;

@Before

public void init(){

//创建配置对象

Configuration config=new Configuration().configure();

//config.addClass(Student.class);

//创建服务注册对象

ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();

//创建会话工厂对象

sessionFactory=config.buildSessionFactory(serviceRegistry);

//会话对象

session=sessionFactory.openSession();

//开启事物

transaction=session.beginTransaction();

}

@After


public void destroy(){

transaction.commit();//提交事物

session.close();//关闭会话

   sessionFactory.close();//关闭会话工厂

}

@Test

public void testSaveStudent(){

 Grade g1=new Grade("java一班","java软件开发一班");

    student1 stu1=new student1("王五","男");

 student1 stu2=new student1("李四","男");

 g1.getStudents().add(stu1);

 g1.getStudents().add(stu2);

 session.save(g1);

 session.save(stu1);

 session.save(stu2);

}

}

http://img.mukewang.com/598c6c5e00016fe304170114.jpg



好好认真学习
浏览 1269回答 1
1回答

呦呦米

报ID存入的ID有重复的,可以看看数据库里 SID是否设置了自动增加,相应的配置文件中 是否设置了自动增加
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java