JPA ArrayList OneToMany UnsupportedOperationException 異常

在使用JPAOneToMany註解,並使用List聲明類型,在更新的操做時,會遇到UnsupportedOperationException異常。java

示例

好比有如下Teacher,對應多個班級shell

public class Teacher {
    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
    private List<Klass> klassList = new ArrayList<>();
}

而後咱們執行以下代碼,則會產生UnsupportedOperationException異常.this

Teacher teacher = teacherRepository.findOne(id);
teacherRepository.save(teacher);

緣由

1.findByOne返回的實體中, klassList的類型是PersistentBag,而非ArrayListspa

clipboard.png

public class PersistentBag extends AbstractPersistentCollection implements List {

2.@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})註解,使得jpa須要對klassList進行如下操做:code

at java.util.AbstractList.clear(AbstractList.java:234)


java.util.AbstractList.clear中,並無具體實現,直接跑出了UnsupportedOperationExceptionip

* @throws UnsupportedOperationException if the {@code remove}
     *         operation is not supported by this list iterator
     * @throws IllegalStateException if neither {@code next} nor
     *         {@code previous} have been called, or {@code remove} or
     *         {@code add} have been called after the last call to
     *         {@code next} or {@code previous}
     */
    void remove();

解決方案

在保存前,強制轉換爲ArrayListrem

Teacher teacher = teacherRepository.findOne(id);
teacher.setKlassList(new ArrayList(teacher.getKlassList()));
teacherRepository.save(teacher);
相關文章
相關標籤/搜索