【发布时间】:2017-01-30 03:17:12
【问题描述】:
我有 2 张桌子。 Book 和 Category。
一本书可以有多个类别,一个类别可以有一个书单,对吧?所以我创建了一个新表category_book 来建立ManyToMany 关系,其中只有book_id(fk) 和category_id(fk)。
我的书实体:
@Id
@Column(name = "book_id", nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int bookId;
@ManyToMany
@JoinTable(name = "category_book", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<CategoryEntity> categoriesList;
...other basic attributes and constructors and getters and setters.....
我的类别实体:
@Id
@Column(name = "category_id", nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int categoryId;
@ManyToMany(mappedBy = "categoriesList", cascade = CascadeType.PERSIST)
private List<BookEntity> bookEntityList;
添加新书的servlet(之前已经单独添加的类别。)
String[] category= request.getParameterValues("checkbox_category");
List<CategoryEntity> categoryEntityList = new ArrayList<>();
BookEntity newbook = new BookEntity();
for(String s: category){
CategoryEntity categoryEntity2 = new CategoryEntity();
categoryEntity2.setCategoryId(Integer.parseInt(s));
categoryEntityList.add(categoryEntity);
}
newbook.setCategories(categoryEntityList);
bookSessionBean.addBook(newbook);
BookSessionBean:
public void addBook(BookEntity book){
em.persist(book);
}
我检查了很多主题,但无法解决问题。错误一直显示。
Internal Exception: java.sql.SQLException: No database selected
Error Code: 1046
Call: INSERT INTO category_book (category_id, book_id) VALUES (?, ?)
bind => [2 parameters bound]
Query: DataModifyQuery(name="categoriesList" sql="INSERT INTO category_book (category_id, book_id) VALUES (?, ?)")
或
Error Code: 1046
Call: ALTER TABLE category_book ADD CONSTRAINT FK_category_book_category_id FOREIGN KEY (category_id) REFERENCES book.category (category_id)
Query: DataModifyQuery(sql="ALTER TABLE category_book ADD CONSTRAINT FK_category_book_category_id FOREIGN KEY (category_id) REFERENCES book.category (category_id)")
其他的都可以坚持成功,只有这个ManyToMany会麻烦。
更新:这不是因为连接URL jdbc,我使用连接池来获取数据库,它是正确的。如果我删除所有相关的@ManyToMany 关系,它将正常运行。但是这次我需要使用ManyToMany关系。
persistence.xml 文件:
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/book</jta-data-source>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
更新2:我只是检查清楚,我试图删除所有与ManyToMany相关的东西,它工作得很好,但是由于我再次添加@ManyToMany,它给出了很多错误,即使它仍然成功部署(但不能添加新书或通过 servlet 和服务会话 bean 添加到新表 category_book)
仍然没有找到解决这个问题的方法。我做错什么了吗?
【问题讨论】:
-
只有在持久化
Category而不是Book时才进行级联,因此在保存一本书时,它应该只在其@ManyToMany关系中附加实体。 -
如果我删除级联或同时添加两者,它仍然给出错误:错误代码:1046 调用:ALTER TABLE category_book ADD CONSTRAINT FK_category_book_category_id FOREIGN KEY (category_id) REFERENCES book.category (category_id)
-
好像你是通过你的持久化提供者自动生成DDL,但这与我的提议无关。