If you delete an immutable collection with JPA, you will naturally get an UnsupportedOperationException.

Normally, you rarely see UnsupportedOperationException. If you inadvertently do a add or `` `remove``` on an immutable collection, that's probably the case.

However, I encountered UnsupportedOperationException in JPA and was addicted to it for a while, so I will leave a note.

What I want to do is to persist a 1: N entity and then delete the child collection for that entity.

	@Transactional
	@Override
	public void run(String... args) throws Exception {
		Parent parent = new Parent(5L, "name", List.of(
				new Child(new ChildId(101L, 1L), "aaa", null),
				new Child(new ChildId(102L, 1L), "bbb", null)
				));
		em.persist(parent);
		
		Parent parent2 = pr.getOne(5L);
		System.out.println(parent == parent2); // true
		List<Child> children = parent2.getChildren();
		parent2.getChildren().clear();
		em.persist(parent2);
	}
Caused by: java.lang.UnsupportedOperationException: null
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:71) ~[na:na]
	at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.clear(ImmutableCollections.java:77) ~[na:na]
	at org.hibernate.collection.internal.PersistentBag.clear(PersistentBag.java:495) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]

With the above code, the same instance is returned for `parent``` and parent2```. Then ``` getChildren``` will return an immutable collection of List.of```, so clear``` will result in `ʻUnsupportedOperationException```.

I didn't immediately notice that the same instance was returned because the actual code was separated from each other in the persistence context. I was unknowingly thinking that if I put it in a persistence context and retrieve it, it would be repacked into a mutable collection such as ArrayList, so the above code would return the same instance. I was addicted to it without noticing it.

Recommended Posts

If you delete an immutable collection with JPA, you will naturally get an UnsupportedOperationException.
If you get tired of drawing an ER diagram
[Rails] What to do if you can't get an error message with the errors method
What to do if you get angry with OpenSSL with pyenv install
[Rails] What to do if you can't get parameters with form_with
What to do if you get an error with bundle install by entering gem'bcrypt' in your Gemfile