在使用JPA
的OneToMany
註解,並使用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
,而非ArrayList
。spa
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
中,並無具體實現,直接跑出了UnsupportedOperationException
ip
* @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
rem
Teacher teacher = teacherRepository.findOne(id); teacher.setKlassList(new ArrayList(teacher.getKlassList())); teacherRepository.save(teacher);