简体   繁体   English

Spring 启动 JPA 获取列表并向其中添加项目会引发错误

[英]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.我正在使用 JPA 并且我有一个名为 Order 的实体/类。 I have a rest GET endpoint to fetch an order by an id.我有一个 rest GET端点来通过 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.现在,在一个特定场景中,我需要从数据库中获取订单并将另一个项目添加到 transactionRefs 并保存它。 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.因此,每当第一次保存 transactionref 时,我们将其转换为 ArrayList。

Update 2:更新 2:

Below is the getter for the transactionRef:下面是 transactionRef 的 getter:

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 . Arrays.asList 返回由数组支持的集合,不能使用addaddAll修改它。 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:更多示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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