Search code examples
javaorientdb

OrientDB one to many using Object API


I'm using the Object API with OrientDB, and I need to change one of my fields. I currently have something like:

class Book { String author }

But I want to change it to:

class Book { List<String> authors }

My question is: how do I persist this list of Strings in OrientDB? Do I have to declare the list as @Embedded? Do I have to define the Schema as LINKLIST?

I tried the latter, which resulted in:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable

And, if I make the type in the database an Embbed, then it results in the error:

Caused by: java.lang.IllegalArgumentException: Type EMBEDDED must be a multi value type (collection or map)

Which doesn't provide to much information unfortunately.

So, how can I best fix this?


Solution

  • Start point: I created a new db from the Java API, and I saved a list of authors.

    CLASS BOOK

    public class Book {
    
    private List<String> authors;
    
    public void setAuthors (List<String> pAuthors){
        this.authors = pAuthors;
    }
    
    public List<String> getAuthors(){
        return this.authors;
    }
    

    }

    CLASS MAIN

    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();
        }
    }
    

    From Studio: the object 'Book' was created, and it has the field 'authors' as embeddedlist. (Created automatically) enter image description here