Ошибка при создании bean-компонента с именем entityManagerFactory, определенным в ресурсе пути к классу, инициализация bean-компонента завершилась неудачно, таблица не найдена - PullRequest
1 голос
/ 05 мая 2020

Я пишу код для веб-приложения, но получаю эту ошибку при создании полей в базе данных. В нем говорится, что таблица "пользователь" не найдена. Я добавляю классы и файл. Это вызывает эту ошибку


2020-05-05 23:04:20.539  WARN 145848 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Spring%20pro%20codeengine/sources/target/classes/data.sql]: insert into user values (1,'Slnmak','Codeengine@gmail.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine@gmail.com') [42102-200]
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-05 23:04:20.803 ERROR 145848 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Spring%20pro%20codeengine/sources/target/classes/data.sql]: insert into user values (1,'Slnmak','Codeengine@gmail.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine@gmail.com') [42102-200]

Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Spring%20pro%20codeengine/sources/target/classes/data.sql]: insert into user values (1,'Slnmak','Codeengine@gmail.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine@gmail.com') [42102-200]

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine@gmail.com') [42102-200]

У меня есть класс категории, как показано ниже. Категория. java

package com.example.sources.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@NoArgsConstructor
@Table(name="category")
public class Category {

    @Id
    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


}

Пользователь. java

package com.example.sources.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
@Table(name="user")
public class User {

    @Id
    private Long id;

    private String name;

    private String email;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

И создал интерфейс репозитория как CategoryRepository. java

package com.example.sources.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.sources.model.Category;

public interface CategoryRepository extends JpaRepository<Category, Long>{

    Category findByName(String name);
}

Data. sql

insert into user values (1,'Slnmak','Codeengine@gmail.com')
insert into user values (2,'John','adam@gmail.com')
insert into user values (3,'Adam','john@gmail.com')

insert into category values (1,'Travel')
insert into category values (2,'Auto Loan')
insert into category values (3,'Student Loan')

--insert into expense values (100,'New York trip','2019-06-16T17:00:00.0002' )
--insert into expense values (101,'Ford Mustang Payment','2019-06-15T15:00:00.0002' )
--insert into expense values (102,'Slnmak Trip with family','2019-06-14T15:00:00.0002' )

application.properties

spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false

пом. xml

    <dependencies>  
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

1 Ответ

0 голосов
/ 05 мая 2020

Приложение не может создавать таблицы автоматически. Замените свой application.properties файл следующим:

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.generate-ddl=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...