[英]java cassandra connection java.lang.ClassNotFoundException: com.datastax.driver.core.Cluster
[英]Cassandra-Java-driver : com.datastax.driver.core.exceptions.InvalidTypeException: Invalid type, column is a list but class java.lang.String provided
我在Cassandra中有一個用戶定義的類型,該類型是我在CQLSH中使用以下語法創建的:
CREATE TYPE order_items (
qty int,
name text,
milk_type text,
size text,
price decimal
);
現在在我的表中,我存儲了一個類型為“ order_items”的列表,因此我可以為一個對象存儲多個項目。
像這樣的東西:
CREATE TABLE order (
order_id uuid PRIMARY KEY,
amount decimal,
location text,
items list<frozen<order_items>>,
status text,
message text
);
如果我想使用CQLSH存儲記錄,則可以使用以下語法,
INSERT INTO order (order_id,amount,location,items,status,message) VALUES
(e7ae5cf3-d358-4d99-b900-85902fda9bb0, 5, 'San Jose',[{qty:2,name:'mocha',milk_type:'whole',size:'small',price:2.5}], 'PLACED','order is in process');
但是,當我嘗試使用DataStax Java驅動程序執行cassandra的操作時,我無法提供用戶定義的類型作為對象列表。 我只能想出一個字符串語法,但是顯然它拋出了以上錯誤。
我曾嘗試參考datastax文檔,但顯然它仍在進行中: http ://docs.datastax.com/en/developer/java-driver/3.1/manual/udts/
這是我的Java語法:
session.execute(insertorderPstmt.bind(UUID.randomUUID(),new BigDecimal("4"),"Santa Clara","[{qty:2,name:'mocha',milk_type:'whole',size:'small',price:2.5}]","PLACED","in process"));
和錯誤:
Exception in thread "main" com.datastax.driver.core.exceptions.InvalidTypeException: Invalid type for value 3, column is a list but class java.lang.String provided
有沒有人能夠使用Java驅動程序存儲自定義類型列表?
您的插入查詢不正確。
如果您使用單引號,則將其用於所有內容,並用逗號分隔所有字段。 如果該字段是字符串,則用引號將其括起來,
使用以下插入查詢:
INSERT INTO order (
order_id,
amount,
location,
items,
status,
message
) VALUES (
e7ae5cf3-d358-4d99-b900-85902fda9bb0,
5,
'San Jose',
[
{qty:2, name:'mocha', milk_type:'whole', size:'small', price:2.5}
],
'PLACED',
'order is in process'
);
使用Java驅動程序:
盡管您要插入用戶定義類型(UDT)值,但是您已經創建了一個自定義編解碼器或使用json
或UDTValue
插入值
這是通過UDTValue插入值的方法:
//First get your UserType from cluster object
UserType oderItemType = cluster.getMetadata()
.getKeyspace(session.getLoggedKeyspace())
.getUserType("order_items");
//Now you can create a UDTValue from your UserType order_items and set value
UDTValue oderItem = oderItemType.newValue()
.setInt("qty", 2)
.setString("name", "mocha")
.setString("milk_type", "whole")
.setString("size", "small")
.setDecimal("price", new BigDecimal(2.5));
// Though you define UDT of List Let's create a list and put the value
List<UDTValue> orders = new ArrayList<>();
orders.add(oderItem);
現在您可以插入如下數據:
//Let your prepared statment be like
PreparedStatement insertorderPstmt = session.prepare("insert into order(order_id,amount,location,items,status,message) values(?, ?, ?, ?, ?, ?)");
//Now you can bind the value and execute query
session.execute(insertorderPstmt.bind(UUID.randomUUID(), new BigDecimal("4"), "Santa Clara", orders, "PLACED", "in process"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.