在使用JPA
的OneToMany
注解,并使用List
声明类型,在更新的操作时,会遇到UnsupportedOperationException
异常。
示例
比如有以下Teacher
,对应多个班级
public class Teacher { @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}) private ListklassList = new ArrayList<>();}
然后我们执行如下代码,则会产生UnsupportedOperationException
异常.
Teacher teacher = teacherRepository.findOne(id);teacherRepository.save(teacher);
原因
1.findByOne
返回的实体中, klassList
的类型是PersistentBag
,而非ArrayList
。
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);