org.h2.jdbc.JdbcSQLException: нарушение ограничения ссылочной целостности - PullRequest
1 голос
/ 20 сентября 2019

Я создаю приложение, которое управляет книгами (книжным магазином) с J2EE (бэкэнд) и Angular (веб-интерфейс), чтобы практиковаться с этими технологиями, но сейчас я сталкиваюсь с проблемой с JPA Hibernate:

У меня есть 2 класса, определенных как сущности, и я храню их в базе данных H2 в памяти: «книга» и «жанр»

Книга принадлежит жанру, и жанр может иметь несколько книг (так что этоотношения один ко многим).

Я также использую Wildfly в качестве своего веб-сервера.Когда я запускаю приложение, H2 создаст мои 2 таблицы и вставит несколько образцов жанра и книг, но я получаю эту ошибку и не могу выяснить проблему в течение 2 дней:

15:09:28,869 WARN  [org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl] (ServerService Thread Pool -- 8) GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement: org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:438)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applyImportSources(SchemaCreatorImpl.java:466)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:179)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:134)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:120)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:148)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:476)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:422)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:880)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:167)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:125)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:650)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:209)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKM1T3YVW5I7OLWDF32CWUUL7TA: PUBLIC.BOOK FOREIGN KEY(GENRE_ID) REFERENCES PUBLIC.GENRE(ID) (5)"; SQL statement:
INSERT INTO BOOK (id, isbn, title, image_url, language, unit_cost, nb_of_pages, publication_date, description, genre_id) VALUES ( 1069, '3319054392', 'ECUMICT 2014: Proceedings of the European Conference', 'http://ecx.images-amazon.com/images/I/418YoIyKXKL._SL160_.jpg', 2, 199.00, 231, DATE '2014-02-23', 'This proceeding present the outcome of the 6th. European Conference on the Use of Modern Information and Communication Technologies. The ECUMICT 2014 was hold in Gent in March 2014 and presented recent research, that has a close relationship with practical implementation of Security for mobile communications and data accessInterface technology for mobile devices Application development for mobile devicesPositioning and localization, asset tracking and tracing Design and applications of RFID systemsDevelopments in the framework of IoT and M2M communicationsDesign and applications of WSNsEmbedded programming for WSNsNew developments and applications of WPAN/WLAN standardsMobile multimedia systemsWireless telecommunication networks and mobile servicesOptimization techniques in wireless networksDevelopments in ad-hoc and mesh networksApplications of digital signal processing for mobile applications Applications of MEMs in WSNs', 5) [23506-193]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRowOwnTable(ConstraintReferential.java:372)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:314)
    at org.h2.table.Table.fireConstraints(Table.java:967)
    at org.h2.table.Table.fireAfterRow(Table.java:985)
    at org.h2.command.dml.Insert.insertRows(Insert.java:161)
    at org.h2.command.dml.Insert.update(Insert.java:114)
    at org.h2.command.CommandContainer.update(CommandContainer.java:98)
    at org.h2.command.Command.executeUpdate(Command.java:258)
    at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:184)
    at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
    at org.jboss.jca.adapters.jdbc.WrappedStatement.execute(WrappedStatement.java:198)
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)

Вотмои 2 предмета:

сущность книги

@Entity
@Table(name="book")
@ApiModel(description = "Book resource representation")
public class Book {

    @Id @GeneratedValue
    @ApiModelProperty("identifier")
    private Long id;

    @Column(length = 200) @NotNull @Size(min = 1, max = 200)
    @ApiModelProperty("title of the book")
    private String title;

    @Column(length = 10000) @Size(min = 1, max = 10000)
    @ApiModelProperty("description of the book")
    private String description;

    @Column(name = "unit_cost") @Min(1)
    @ApiModelProperty("unit cost of the book")
    private Float unitCost;

    @NotNull @Size(min = 1, max = 15)
    @ApiModelProperty("isbn of the book")
    private String isbn;

    @Column(name = "publication_date")
    @Temporal(TemporalType.DATE)
    @Past
    @ApiModelProperty("publication date of the book")
    private Date publicationDate;

    @Column(name = "nb_of_pages")
    @ApiModelProperty("number of pages of the book")
    private Integer nbOfPages;

    @Column(name = "image_url")
    @ApiModelProperty("url of the book image")
    private String imageUrl;

    @Enumerated(EnumType.ORDINAL)
    @ApiModelProperty("language of the book")
    private Language language;

    @ManyToOne(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    @ApiModelProperty("genre of the book")
    @JoinColumn(name = "genre_id", nullable = false)
    private Genre genre;


    public Book() {
    }

    public Genre getGenre() {
        return genre;
    }

    public void setGenre(Genre genre) {
        this.genre = genre;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Float getUnitCost() {
        return unitCost;
    }

    public void setUnitCost(Float unitCost) {
        this.unitCost = unitCost;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public Date getPublicationDate() {
        return publicationDate;
    }

    public void setPublicationDate(Date publicationDate) {
        this.publicationDate = publicationDate;
    }

    public Integer getNbOfPages() {
        return nbOfPages;
    }

    public void setNbOfPages(Integer nbOfPages) {
        this.nbOfPages = nbOfPages;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public Language getLanguage() {
        return language;
    }

    public void setLanguage(Language language) {
        this.language = language;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", description='" + description + '\'' +
                ", unitCost=" + unitCost +
                ", isbn='" + isbn + '\'' +
                ", publicationDate=" + publicationDate +
                ", nbOfPages=" + nbOfPages +
                ", imageUrl='" + imageUrl + '\'' +
                ", language=" + language +
                '}';
    }

сущность жанра:

@Entity
@Table(name="genre")
@ApiModel(description = "Genre of a book resource representation")
public class Genre {

    @Id @GeneratedValue
    @ApiModelProperty("identifier")
    private Long id;

    @Column(length = 200) @NotNull
    @Size(min = 1, max = 200)
    @ApiModelProperty("name of the genre")
    private String title;

    @OneToMany(mappedBy = "genre", cascade = CascadeType.ALL)
    private List<Book> books;

    public Genre() {
        this.books = new ArrayList<Book>();
    }

    public Genre(String title) {
        this.title = title;
        this.books = new ArrayList<Book>();
    }

    public Long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public List<Book> getBooks() {
        return books;
    }
}

единица моей персистентности:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">

    <persistence-unit name="bookstorePU">
        <class>com.learning.bookstore.model.Book</class>
        <class>com.learning.bookstore.model.Genre</class>
        <properties>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/>
            <property name="javax.persistence.schema-generation.scripts.create-target" value="bookStoreCreate.dll"/>
            <property name="javax.persistence.schema-generation.scripts.drop-target" value="bookStoreDrop.dll"/>
            <property name="javax.persistence.sql-load-script-source" value="import.sql"/>
        </properties>
    </persistence-unit>
</persistence>

мой sqlскрипт, импортированный H2:

DELETE FROM genre;
DELETE FROM book;


INSERT INTO GENRE (id, title) VALUES (1, "Database & Big Data")
INSERT INTO GENRE (id, title) VALUES (2, "Networking & Cloud")
INSERT INTO GENRE (id, title) VALUES (3, "Operating Systems")
INSERT INTO GENRE (id, title) VALUES (4, "Programming")
INSERT INTO GENRE (id, title) VALUES (5, "Security & Encryption")
INSERT INTO GENRE (id, title) VALUES (6, "Web development & Design")

INSERT INTO BOOK (id, isbn, title, image_url, language, unit_cost, nb_of_pages, publication_date, description, genre_id) VALUES ( 1001, '1931182310', 'Advanced Java EE Development for RAD Guidebook', 'http://ecx.images-amazon.com/images/I/51bjnhlGbeL._SL160_.jpg', 2, 79.95, 752, DATE '2011-11-21', 'Written by IBM senior field engineers and senior product development experts, this advanced book provides a solid look at the development of a range of core Java EE technologies, as well as an in-depth description of the development facilities provided by IBM Rational Application Developer version 7.5. Since the Java EE developmental platform incorporates a wide range of technologies from disparate and myriad sources, this up-to-date guidebook helps developers triumph over the complexity and depth of knowledge required to build successful architectures. Senior developers, engineers, and architects—especially those who work with Rational Application Developer and those seeking certification at the Sun-certified Java master-tier level or the IBM Rational Application Developer certified professional and certified advanced professional levels—will appreciate this convenient, single reference point.', 1)
INSERT INTO BOOK (id, isbn, title, image_url, language, unit_cost, nb_of_pages, publication_date, description, genre_id) VALUES ( 1002, '1931182311', 'Advanced Java EE Development for RAD Guidebook (Nov-2011)', 'http://ecx.images-amazon.com/images/I/511pqkJd3UL._SL160_.jpg', 2, 9.99, 543, DATE '2011-11-21', 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc', 2)
INSERT INTO BOOK (id, isbn, title, image_url, language, unit_cost, nb_of_pages, publication_date, description, genre_id) VALUES ( 1003, '1931182312', 'Advanced Java EE Development for RAD Guidebook 2nd', 'http://ecx.images-amazon.com/images/I/511pqkJd3UL._SL160_.jpg', 4, 9.99, 987, DATE '2005-09-17', 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc', 3)
INSERT INTO BOOK (id, isbn, title, image_url, language, unit_cost, nb_of_pages, publication_date, description, genre_id) VALUES ( 1004, '1514210959', 'Advanced Java EE Development with WildFly', 'http://ecx.images-amazon.com/images/I/51f7V8CEb7L._SL160_.jpg', 7, 44.99, 416, DATE '2015-06-04', 'Your one-stop guide to developing Java® EE applications with the Eclipse IDE, Maven, and WildFly® 8.1 About This Book •Develop Java EE 7 applications using the WildFly platform •Discover how to use EJB 3.x, JSF 2.x, Ajax, JAX-RS, JAX-WS, and Spring with WildFly 8.1 •A practical guide filled with easy-to-understand programming examples to help you gain hands-on experience with Java EE development using WildFly Who This Book Is For This book is for professional WildFly developers. If you are already using JBoss or WildFly but don''t use the Eclipse IDE and Maven for development, this book will show you how the Eclipse IDE and Maven facilitate the development of Java EE applications with WildFly 8.1. This book does not provide a beginner-level introduction to Java EE as it is written as an intermediate/advanced course in Java EE development with WildFly 8.1. In Detail This book starts with an introduction to EJB 3 and how to set up the environment, including the configuration of a MySQL database for use with WildFly. We will then develop object-relational mapping with Hibernate 4, build and package the application with Maven, and then deploy it in WildFly 8.1, followed by a demonstration of the use of Facelets in a web application. Moving on from that, we will create an Ajax application in the Eclipse IDE, compile and package it using Maven, and run the web application on WildFly 8.1 with a MySQL database. In the final leg of this book, we will discuss support for generating and parsing JSON with WildFly 8.1.', 4)
INSERT INTO BOOK (id, isbn, title, image_url, language, unit_cost, nb_of_pages, publication_date, description, genre_id) VALUES ( 1005, '8894038912', 'Advanced Jax-Ws Web Services', 'http://ecx.images-amazon.com/images/I/31lRGN%2BfvDL._SL160_.jpg', 6, 22.90, 154, DATE '2014-11-02', 'In this book you''ll learn the concepts of Soap based Web Services architecture and get practical advice on building and deploying Web Services in the enterprise. Starting from the basics and the best practices for setting up a development environment, this book enters into the inner details of the Jax-Ws in a clear and concise way. You will also learn about the major toolkits available for creating, compiling and testing Soap Web Services and how to address common issues such as debugging data and securing its content. What you will learn: Move your first steps with Soap Web Services. Developing Web Services using top-down and bottom-up approach. Using Maven archetypes to speed up Web Services creation. Getting into the details of Jax-Ws types: Java to Xml mapping and Xml to Java Developing Soap Web Services on WildFly 8 and Tomcat. Running native Apache Cxf on WildFly Securing Web Services. Applying authentication policies to your services. Encrypting the communication.', 5)
INSERT INTO BOOK (id, isbn, title, image_url, language, unit_cost, nb_of_pages, publication_date, description, genre_id) VALUES ( 1006, '0071763929', 'Mike Meyers'' Guide to Supporting Windows 7', 'http://ecx.images-amazon.com/images/I/51Dk-Zq2I7L._SL160_.jpg', 5, 30.00, 240, DATE '2011-09-15', 'Mike Meyers'' Guide to Supporting Windows 7 for CompTIA A+ Certification, Exams 220-701 & 220-702 Get the latest information on the new Windows 7 topics and questions added to CompTIA A+ exams 220-701 and 220-702. A must-have companion to CompTIA A+ All-in-One Exam Guide, Seventh Edition andMike Meyers'' CompTIA A+ Guide to Managing and Troubleshooting PCs, Third Edition, this book focuses on the new exam objectives. Mike Meyers'' Guide to Supporting Windows 7 for CompTIA A+ Certification provides learning objectives at the beginning of each chapter, exam tips, practice exam questions, and in-depth explanations. Written by the leading authority on CompTIA A+ certification and training, this essential resource provides the up-to-date coverage you need to pass the exams with ease. Mike Meyers, CompTIA A+, CompTIA Network+, CompTIA Security+, MCP, is the industry''s leading authority on CompTIA A+ certification and the bestselling author of seven editions of CompTIA A+ All-in-One Exam Guide. He is the president of PC and network repair seminars for thousands of organizations throughout the world, and a member of CompTIA.', 6)
/*
...