我正在使用 OrientDB 的对象 API,并且我需要更改我的字段之一。我目前有类似的东西:
class Book { String author }
但我想将其更改为:
class Book { List<String> authors }
我的问题是:如何在 OrientDB 中保留这个字符串列表?我是否必须将列表声明为@Embedded?我必须将架构定义为链接列表吗?
我尝试了后者,结果是:
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable
而且,如果我将数据库中的类型设置为 Embed,则会导致错误:
Caused by: java.lang.IllegalArgumentException: Type EMBEDDED must be a multi value type (collection or map)
不幸的是,这并没有提供太多信息。
那么,我怎样才能最好地解决这个问题呢?
最佳答案
起点: 我从 Java API 创建了一个新数据库,并保存了作者列表。
类(class)书
public class Book {
private List<String> authors;
public void setAuthors (List<String> pAuthors){
this.authors = pAuthors;
}
public List<String> getAuthors(){
return this.authors;
}
}
主类
public class DatabaseTipoObject {
private static String remote="remote:localhost/";
public static void main(String[] args) {
String nomeDb="Object";
String path=remote+nomeDb;
try {
OServerAdmin serverAdmin = new OServerAdmin(path).connect("root", "root");
if(serverAdmin.existsDatabase()){
System.out.println("Database '"+nomeDb +"' exist..");
}
else{
serverAdmin.createDatabase(nomeDb, "object", "plocal");
System.out.println(" Database '"+nomeDb +"' created!..");
}
OObjectDatabaseTx db = new OObjectDatabaseTx (path);
db.open("root","root");
db.getEntityManager().registerEntityClass(Book.class);
Book book = db.newInstance(Book.class);
List<String> myAuthors = new ArrayList();
myAuthors.add("Archimede");
myAuthors.add("Pitagora");
book.setAuthors(myAuthors);
db.save(book);
System.out.println("Data inserted!" );
//get info by query
for (Book book_retrive : db.browseClass(Book.class)) {
System.out.println("#: " +book_retrive.getAuthors().get(0) );
System.out.println("#: " +book_retrive.getAuthors().get(1) );
}
db.close();
serverAdmin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
关于java - OrientDB 使用对象 API 一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452701/