1

我不明白如何实现与 Vaadin 的 SQLContainer 的外键关系。假设我有两个表:

  1. 带有属性title和 *author_id*的书
  2. AUTHOR 具有属性 *id_author、first_name* 和 *last_name*

当然 BOOK.author_id 引用了 AUTHOR.id 我已经创建了一个具有所有必要约束的 MySQL-DB。此外,我创建了容器并按如下方式填充它们:

private static void initContainers() {
    try {
        /* TableQuery and SQLContainer for book -table */
        TableQuery q1 = new TableQuery("book", connectionPool);
        bookContainer = new SQLContainer(q1);

        /* TableQuery and SQLContainer for author -table */
        TableQuery q2 = new TableQuery("author", connectionPool);
        authorContainer = new SQLContainer(q2);


    } catch (SQLException e) {
        e.printStackTrace();
    }
}

@SuppressWarnings("unchecked")
public boolean addBook(Book book) {
    Object id_author = authorContainer.addItem();
    authorContainer.getContainerProperty(id_author,  "first_name").setValue(book.getAuthor().getFirstName());
    authorContainer.getContainerProperty(id_author, "last_name").setValue(book.getAuthor().getLastName());      

    Object id = bookContainer.addItem();   
    bookContainer.getContainerProperty(id, "title").setValue(book.getTitle());         

//HERE IS MY TRY FOR ADDING THE REFERENCE (FOREIGN KEY RELATION)
    bookContainer.addReference(authorContainer, "author_id", "id_author");         
    authorContainer.setReferencedItem("id_author", "author_id", bookContainer);
    bookContainer.getContainerProperty(id, "author").setValue(bookContainer.getReferencedItem("id_author", authorContainer)); 

    try {
        authorContainer.commit();
        bookContainer.commit();
        return true;
    } catch (UnsupportedOperationException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}

谁能告诉我我在这里做错了什么?我还尝试在添加引用之前提交作者容器,但这也不起作用。

我总是在 *bookContainer.getReferencedItem("id_author", authorContainer)* 处得到 NullPointerException

4

1 回答 1

1

尝试authorContainer.getReferencedItem("id_author", bookContainer)

于 2013-09-28T15:09:27.520 回答