简体   繁体   English

JPA持续存在ManyToMany错误未选择数据库

[英]JPA Persist ManyToMany Error No database selected

I have 2 tables. 我有2张桌子。 Book and Category . BookCategory A book can have multiple categories, and a category can have a list of book, right? 一本书可以有多个类别,一个类别可以有一个图书清单,对吗? So I create a new table category_book to make a ManyToMany relationship, with only book_id(fk) and category_id(fk) in it. 因此,我创建了一个新表category_book来建立ManyToMany关系,其中仅包含book_id(fk)和category_id(fk)。

My Book Entity: 我的图书实体:

 @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.....

My Category Entity: 我的类别实体:

@Id
@Column(name = "category_id", nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int categoryId;

@ManyToMany(mappedBy = "categoriesList", cascade = CascadeType.PERSIST)
private List<BookEntity> bookEntityList;

The servlet to add new book (categories already added seperately before.) 用于添加新书的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: BookSessionBean:

public void addBook(BookEntity book){
    em.persist(book);
}

I checked many topics, but couldn't solve the problem. 我检查了许多主题,但无法解决问题。 The error keeps showing. 错误持续显示。

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 (?, ?)")

or 要么

    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)")

All other things can persist successfully, only this ManyToMany cause troubles. 所有其他事情都可以成功持续,只有这ManyToMany会引起麻烦。

UPDATE: It's not because of connection URL jdbc, I'm using connection pool to get database and it's correct. 更新:不是因为连接URL jdbc,我使用连接池来获取数据库,这是正确的。 If I remove the all the @ManyToMany relationship related, it will run normal. 如果删除所有相关的@ManyToMany关系,它将正常运行。 But this time I need to use ManyToMany relationship. 但是这一次我需要使用ManyToMany关系。

The persistence.xml file: 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>

UPDATE 2: I just check clearly, I tried to remove all ManyToMany related, it's working perfectly, but since I add @ManyToMany back again, it gives many errors, even it's still deploys successfully (but can't add new book or add to new table category_book via servlet and service session bean ) 更新2:我只是清楚地检查,我试图删除所有与ManyToMany相关的,它工作正常,但是由于我又添加了@ManyToMany,所以它给出了很多错误,即使它仍然可以成功部署(但是不能添加新书或添加到通过servlet和服务会话bean新建表category_book

Still haven't find anything to solve this problem. 仍然没有找到任何解决该问题的方法。 Am I doing anything wrong? 我做错什么了吗?

Well, this can only mean you haven't configured the persistance.xml correctly. 好吧,这仅意味着您没有正确配置persistance.xml。

The way the connection url should look like is: 连接网址应如下所示:

"jdbc:databaseType://ip:port/databaseName"

example: "jdbc:mysql://localhost:3306/books"

So, after of hours and hours researching on the internet what's the problem, but no help. 因此,经过数小时的互联网研究,问题出在哪里,但无济于事。 Then at some point I tried to look into the error message, and the problem is the one I find it hard to understand, no other place ever mentions it. 然后在某个时候我试图查看错误消息,问题是我发现很难理解的错误,没有其他地方提到过。

The error No Database Selected is because of the name column in the @ManyToMany @JoinTable annotation. 错误“未选择数据库”是由于@ManyToMany @JoinTable批注中的名称列。 I need to put the databasename.columnname then it's working. 我需要输入databasename.columnname然后它才能正常工作。 But I check many many tutorials and some answers/questions here, they dont need databasename , weird, right? 但是我在这里检查了许多教程和一些答案/问题,它们不需要databasename ,很奇怪,对吗? And If I use @Column I dont need databasename at all. 而且,如果我使用@Column我根本不需要databasename

@Id
@Column(name = "book_id", nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private String bookId

    @ManyToMany(cascade = CascadeType.MERGE)
@JoinTable(name = "book.category_book", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "category_id"))
//The correct one. `book` is my databasename. 

To get the code working more correctly, because in table category_book I have 2 primary keys book_id and category_id (works as foreign key), I have to change the ArrayList to HashSet to allow duplicated keys. 为了使代码更正确地工作,因为在表category_book我有2个主键book_idcategory_id (用作外键),我必须将ArrayList更改为HashSet以允许重复的键。

private Set<CategoryEntity> categoriesList = new HashSet<>();

I remove casdade for CategoryEntity, add cascade MERGE for BookEntity. 我为CategoryEntity删除了casdade,为BookEntity添加了层叠MERGE。

Now everything's working and running. 现在一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM