在Hibernate单向一对多关联关系中的org.hibernate.StaleStateException 异常。

具体异常如下:

Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:59)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate

原因之一:先保存一端的对象,再保存多端的对象

具体代码如下。

@Test
    public void testTeamAndMember()
    {
        Team team = new Team();
        team.setId(1);
        team.setName("A队");
        
        Member member1 = new Member();
        member1.setId(1);
        member1.setName("AA");
        
        Member member2 = new Member();
        member2.setId(2);
        member2.setName("BB");
        
        //设定关联关系
        team.getMembers().add(member1);
        team.getMembers().add(member2);
        
        //在这个单项一对多关联关系中,先保存一端的对象,再保存多端的对象,就会抛出
        //Caused by: org.hibernate.StaleStateException: 的异常。
        testService.saveTeam(team);
        testService.saveMember(member1);
        testService.saveMember(member2);
        
    }

把以上代码改为,先保存多端的对象,再保存一端的对象就可以避免异常了。

具体代码如下:

@Test
    public void testTeamAndMember()
    {
        Team team = new Team();
        team.setId(1);
        team.setName("A队");
        
        Member member1 = new Member();
        member1.setId(1);
        member1.setName("AA");
        
        Member member2 = new Member();
        member2.setId(2);
        member2.setName("BB");
        
        //设定关联关系
        team.getMembers().add(member1);
        team.getMembers().add(member2);
        
        //在这个单项一对多关联关系中,先保存多端的对象,再保存一端的对象,就不会抛出异常。
        testService.saveMember(member1);
        testService.saveMember(member2);
        
        testService.saveTeam(team);
    }

 

posted @ 2017-07-18 10:20  钓鱼翁  阅读(339)  评论(0编辑  收藏  举报