InvalidTypeException: значение 0 класса типа java .util.ArrayList не соответствует ни одному типу CQL3 - PullRequest
2 голосов
/ 09 марта 2020

Я пытаюсь добавить замороженный список с помощью UDT, но я получаю это исключение:

org.springframework.data.cassandra.CassandraTypeMismatchException: Query; CQL [UPDATE docs SET items=items+? WHERE ip=?]; Value 0 of type class java.util.ArrayList does not correspond to any CQL3 type; nested exception is com.datastax.driver.core.exceptions.InvalidTypeException: Value 0 of type class java.util.ArrayList does not correspond to any CQL3 type

Я создал UDT так:

CREATE TYPE item (
    type text,
    uuid text,
    timestamp bigint,
    size bigint,
    content text
);

И вот такая таблица :

CREATE TABLE docs (
    ip text PRIMARY KEY,
    items list<frozen<item>>,
    keys list<text>
);

Здесь POJO docs:

@Table("docs")
public class Document implements Serializable {

    private static final long serialVersionUID = 1L;

    @PrimaryKey
    private String ip;
    private List<String> keys;
    private List<Item> items;

    public void setIp(String ip) {
        this.ip = ip;
    }
    public void addNewKey(String key) {
        this.keys.add(key);
    }
    public void addNewItem(Item item) {
        this.items.add(item);
    }

    public Document(String ip) {
        this.ip = ip;
        this.keys = new ArrayList<String>();
        this.items = new ArrayList<Item>();
    }

    public List<Item> getAllItems() {
        return items;
    }
    public int getAllItemsLength() {
        try {
            return items.size();
        } catch (Exception e) {
            return 0;
        }
    }
    public List<String> getAllKeys() {
        return keys;
    }
    public int getAllKeysLength() {
        try {
            return keys.size();
        } catch (Exception e) {
            return 0;
        }
    }

    public String getAsJsonString() {
        return new Gson().toJson(this);
    }
}

Здесь POJO UDT:

@UserDefinedType(value="item")
public class Item implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull
    private String type;
    @NotNull
    private String uuid;
    @NotNull
    private long timestamp;
    @NotNull
    private long size;
    @NotNull
    private String content;

    public Item(String type, String uuid, long timestamp, long size, String content) {
        this.type = type;
        this.uuid = uuid;
        this.timestamp = timestamp;
        this.size = size;
        this.content = content;
    }
}

Здесь хранилище:

@Query(value="UPDATE docs SET items=items+?0 WHERE ip=?1")
@AllowFiltering
public void updateItemByIp(List<Item> item, String ip);

Вот служба, где я вызываю updateItemByIp ():

Item thatItem = new Item(
  "text/plain",
  "hrT4qLrWt1m3vwLU0smlIkwJJS7Y+/KhTudPwVCWf3w=",
  1583782576724,
  26,
  "content"
);
List<Item> itemList = new ArrayList<Item>();
itemList.add(thatItem);

DBRepo.updateItemByIp(itemList, ip); // <-- The exception is triggered here with IDE breakpoints

Когда я делаю тот же запрос в cql sh, он отлично работает.

Это мой первый вопрос тут, надеюсь меня поняли, всем спасибо за помощь:)

1 Ответ

0 голосов
/ 11 апреля 2020

Решением было использование методов, реализованных в репозитории: findById() и save() вместо моего собственного метода updateItemByIp(), например:

// inject the repository in the class
@Autowired
private DocumentsRepository DBRepo;

// ...

final Optional<Document> query = DBRepo.findById(923216);
if (query.isPresent()) {

    // create new item
    Item thatItem = new Item(
        "text/plain",
        "hrT4qLrWt1m3vwLU0smlIkwJJS7Y+/KhTudPwVCWf3w=",
        1583782576724,
        26,
        "content"
    );

    // add item to database
    query.map(dbDocument -> {
        dbDocument.addNewItem(thatItem);
        return DBRepo.save(dbDocument);
    });
};

И это прекрасно работает!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...