UnsupportedOperationException merge-saving many-to-many relation with hibernate and JPA

后端 未结 2 1554
广开言路
广开言路 2020-12-09 14:37

I\'ve set up a simple many-to-many relationship account : role with Hibernate but when I try to save an account in a unit test after it has had its role added I get an Unsup

相关标签:
2条回答
  • 2020-12-09 14:57

    Hibernate's persistent variant of the Collection in question attempts to delegate to an abstract base class (PersistenceBag) that doesn't implement the add method.

    0 讨论(0)
  • 2020-12-09 15:15

    It is because of your

    Arrays.asList(roleProvider.findAll().get(0))
    

    This creates an unmodifiable list (in fact, a non-resizable list). Hibernate seems to expect a modifiable list. Try using this instead:

    public void testAccountRole(){      
        Account returnedAccount = accountProvider.findAll().get(0);
    
        List<Role> list = new ArrayList<Role>();
        list.add(roleProvider.findAll().get(0));    
        returnedAccount.setRoles(list);  
    
        accountProvider.save(returnedAccount);
    }
    

    This solution won't explain why exactly you got the other exception (might be documented in the Hibernate docs), but it might be a valid workaround.

    0 讨论(0)
提交回复
热议问题