JPA ArrayList OneToMany UnsupportedOperationException 异常

在使用JPAOneToMany注解,并使用List声明类型,在更新的操作时,会遇到UnsupportedOperationException异常。

示例

比如有以下Teacher,对应多个班级

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

然后我们执行如下代码,则会产生UnsupportedOperationException异常.

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

原因

1.findByOne返回的实体中, klassList的类型是PersistentBag,而非ArrayList

clipboard.png

public class PersistentBag extends AbstractPersistentCollection implements List {

2.@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})注解,使得jpa需要对klassList进行以下操作:

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


java.util.AbstractList.clear中,并没有具体实现,直接跑出了UnsupportedOperationException

     * @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();

解决方案

在保存前,强制转换为ArrayList


Teacher teacher = teacherRepository.findOne(id);
teacher.setKlassList(new ArrayList(teacher.getKlassList()));
teacherRepository.save(teacher);

你可能感兴趣的:(jpa,exception)