简体   繁体   中英

Spring boot JPA fetch a list and add an item to it throws error

I am using JPA and I have an entity/class named Order. I have a rest GET endpoint to fetch an order by an id. It works perfectly fine. The order entity looks like below:

@Entity
public class Order {

@Id
private Long id;

@Column
private List<String> transactionRefs;
}

Now, in one particular scenario, I need to fetch the order from the database and add another item to the transactionRefs and save it. So I do as below:

Order order = orderRepository.findById(1).get();
List<String> transactionList = order.getTransactionRefs();
transactionList.add("transaction-ref");

I get the below error when I do that:

java.lang.UnsupportedOperationException: null\n\tat java.util.AbstractList.add(AbstractList.java:148)

If I do as below, that fixes the problem:

Order order = orderRepository.findById(1).get();
List<String> transactionList = order.getTransactionRefs();
transactionList = new ArrayList<>(transactionList);
transactionList.add("transaction-ref");

So, I need to know if I am in the right direction here and is this an expected error scenario.

Update:

Whenever we are adding an item to the list, we have the below condition:

if (transactionRefs == null) {
        transactionRefs = new ArrayList<>();
}

So, whenever the transactionref is saved for the first time, we cast it to a ArrayList.

Update 2:

Below is the getter for the transactionRef:

public List<String> getTransactionRefs(){
    if (this.transactionRefs != null) {
        return Arrays.asList(this.transactionRefs.split(","));
    }
    return null;
}

This is the cause of your exception

return Arrays.asList(this.transactionRefs.split(","));

Arrays.asList returns a collection backed by the array and it can't be modified with add or addAll . You need to create the List just like you are doing in the question:

List<String> transactionList = order.getTransactionRefs();
transactionList = new ArrayList<>(transactionList);

For more examples:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM