Table 未创建 JPA

Table doesn't get created JPA

Table “书籍”无法以某种方式创建。

我的书table:

@Entity
@Table(name = "books")
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
private Long id;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "publisher_id", nullable = false)
private Publisher publisher;

@ManyToMany
@JoinTable(name = "authors_books", joinColumns = @JoinColumn(name = "book_id"),
        inverseJoinColumns = @JoinColumn(name = "author_id"))
private Set<Author> authors;

@Column(name = "is_rented", nullable = false, columnDefinition = "DEFAULT FALSE")
private Boolean is_rented;
  
@Column(name = "isbn", nullable = false, unique = true, length = 300)
private String isbn;

出版商table:

@Entity
@Table(name = "publishers")
public class Publisher {
   @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @OneToMany(mappedBy = "publisher")
    private Set<Book> books;

作者table:

@Entity
@Table(name = "authors")
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @ManyToMany(mappedBy = "authors")
    private Set<Book> books;

application.properties:

spring.jpa.hibernate.ddl-auto=create
spring.jpa.database=mysql
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/<schema_name>?createDatabaseIfNotExist=true
spring.datasource.username=${MYSQL_USERNAME}
spring.datasource.password=${MYSQL_PASSWORD}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

省略其他字段,只留下参考字段。我还在所有实体中覆盖了 equals 和 hashcode 方法。我有空的构造函数和完整的构造函数,以及所有这些构造函数中的 getter 和 setter。还在 SpringBootApplication 文件中添加了@EntityScan。

我收到错误:

Table '<schema_name>.authors_books' doesn't exist.
Table '<schema_name>.books' doesn't exist.

但所有其他 table 确实存在。有人看到我遗漏了什么吗?

编辑

手动检查数据库。 Table“authors_books”确实存在(尽管 jpa 告诉我它不存在)。只有“书”没有。

编辑#2

我添加到application.properties:

spring.jpa.show-sql=真 spring.jpa.properties.hibernate.format_sql=真

它告诉我:

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "
    create table books (
       id bigint not null,
        amount integer not null,
        image varchar(300),
        is_rented DEFAULT FALSE,
        isbn varchar(300) not null,
        published_on date,
        title varchar(300) not null,
        publisher_id bigint not null,
        primary key (id)
    ) engine=InnoDB"

原因:java.sql.SQLSyntaxErrorException:您的 SQL 语法有误;查看与您的 MySQL 服务器版本对应的手册,了解在“DEFAULT FALSE”附近使用的正确语法, isbn varchar(300) 不为空, ' 在第 5 行

看起来问题出在:

@Column(name = "is_rented", nullable = false, columnDefinition = "DEFAULT FALSE")
private Boolean is_rented;

如果您配置 columnDefinition,则 Hibernate 不关心您提供的 java-based 数据类型。

所以 SQL 就像:

is_rented DEFAULT FALSE,
  • 明显缺少数据类型

所以我改成:

@Column(name = "is_rented", columnDefinition = "BOOLEAN DEFAULT FALSE")
private Boolean is_rented;

它奏效了:)