I have the following entity:
@Entity(name = "courses")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Singular
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Collection<Comment> comments = new ArrayList<>();
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private User createdBy;
public void addComment(Comment comment) {
comments.add(comment);
}
}
When I load a course from the database, comments are initialized with a Persistent Bag. The problem occurs when I call addComment(comment), I then get this exception:
Caused by: java.lang.UnsupportedOperationException: null
at java.base/java.util.AbstractList.add(AbstractList.java:153) ~[na:na]
at java.base/java.util.AbstractList.add(AbstractList.java:111) ~[na:na]
at org.hibernate.collection.internal.PersistentBag.add(PersistentBag.java:408) ~[hibernate-core-5.4.18.Final.jar:5.4.18.Final]
It seems that the Persistant Bag, which hibernates assigns, is a Collection.EmptyList, which is immutable and, as such, no comments can be added.
What do I need to change to be able to add comments?