我不知道如何与Vaadin的SQLContainer实现外键关系。 我们假设我有两个表:
Coure 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;
}
谁能告诉我这里做错了什么?我还尝试在添加引用之前提交author-container,但这也不起作用。
我总是在* bookContainer.getReferencedItem(“id_author”,authorContainer)*
获得NullPointerException答案 0 :(得分:1)
尝试authorContainer.getReferencedItem("id_author", bookContainer)