无法使用 Spring Boot 和 JPA 在数据库中创建表

发布于 2025-01-15 20:28:37 字数 4026 浏览 0 评论 0原文

当我使用 Spring Boot 应用程序和 JPA 在名为 schooldb 的数据库中创建一个表时,代码运行良好,但我无法自动创建表,并且必须使用 CMD 或任何其他终端显式创建它。 IDE。

这是我的存储库类

package com.jpabasics.jpaBasics.enitity;

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

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

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student {

    @Id
     private long studentId;
     private String firstName;
     private String lastName;
     private String emailId;
     private String guardianName;
     private String guardianEmail;
     private String guardianMobile;


}

,这是我的 POM.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jpabasics</groupId>
    <artifactId>jpaBasics</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jpaBasics</name>
    <description>Jpa basics</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <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>mysql</groupId>
            <artifactId>mysql-connector-java</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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

另外,这是我的 application.properties 文件

# Database Config : mysql
spring.datasource.url = jdbc:mysql://localhost:3306/schooldb
spring.datasource.username = root
spring.datasource.password = Lko@6388895330
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

# Hibernate Configuration
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl.auto = update
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect

有人可以帮我解决这个问题吗?

When I am using my Spring Boot application along with JPA to create a table in my database named schooldb, the code runs fine but I am unable to automatically create a table and have to explicitly create it either using the CMD or any other terminal in an IDE.

Here is my repository class

package com.jpabasics.jpaBasics.enitity;

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

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

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student {

    @Id
     private long studentId;
     private String firstName;
     private String lastName;
     private String emailId;
     private String guardianName;
     private String guardianEmail;
     private String guardianMobile;


}

and here is my POM.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jpabasics</groupId>
    <artifactId>jpaBasics</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jpaBasics</name>
    <description>Jpa basics</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <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>mysql</groupId>
            <artifactId>mysql-connector-java</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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Also here is my application.properties file

# Database Config : mysql
spring.datasource.url = jdbc:mysql://localhost:3306/schooldb
spring.datasource.username = root
spring.datasource.password = Lko@6388895330
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

# Hibernate Configuration
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl.auto = update
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect

Could someone help me out with this please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时浪漫 2025-01-22 20:28:37

您缺少在数据库中构建表来托管实体所需的 @table 注释。另外,对列进行注释也是一个很好的习惯,以确保它们的命名正确(尽管在您的情况下,它们会被正确解析)。例如:

package com.jpabasics.jpaBasics.enitity;

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

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

@Entity
@Table(name="STUDENTS")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student {

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     @Column(name = "STUDENT_ID")
     private long studentId;

     @Column(name = "FIRST_NAME")
     private String firstName;

     @Column(name = "LAST_NAME")
     private String lastName;

     @Column(name = "EMAIL_ID")
     private String emailId;

     @Column(name = "GUARDIAN_NAME")
     private String guardianName;

     @Column(name = "GUARDIAN_EMAIL")
     private String guardianEmail;

     @Column(name = "GUARDIAN_MOBILE")
     private String guardianMobile;

}

You're missing the @table annotation which is required to build a table in your DB to host the entities. Also, it's good custom to annotate your columns as well, to make sure they're named correctly (although in your case, they would've been correctly parsed). For example:

package com.jpabasics.jpaBasics.enitity;

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

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

@Entity
@Table(name="STUDENTS")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student {

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     @Column(name = "STUDENT_ID")
     private long studentId;

     @Column(name = "FIRST_NAME")
     private String firstName;

     @Column(name = "LAST_NAME")
     private String lastName;

     @Column(name = "EMAIL_ID")
     private String emailId;

     @Column(name = "GUARDIAN_NAME")
     private String guardianName;

     @Column(name = "GUARDIAN_EMAIL")
     private String guardianEmail;

     @Column(name = "GUARDIAN_MOBILE")
     private String guardianMobile;

}
说不完的你爱 2025-01-22 20:28:37

我使用相同的代码,但仍然无法创建表。

请查找以下日志

。 ____ _ __ _ _
/\ / ' __ _ () __ __ _ \ \ \
( ( )_
_ | '_ | '| | ' / ` | \ \ \
\/ __)| |)| | | | | || (
| | ) ) ) )
' || .__|| ||| |_, | ////
=========|
|==============|
/=///< /em>/
:: Spring Boot :: (v3.1.1)

2023-07-24T13:43:17.936+05:30  INFO 9080 --- [           main] c.e.S.SpringJpaTestApplication           : Starting SpringJpaTestApplication using Java 17.0.7 with PID 9080 (C:\Users\arpit.verma\Downloads\SpringJPATest\SpringJPATest\target\classes started by arpit.verma in C:\Users\arpit.verma\Downloads\SpringJPATest\SpringJPATest)
2023-07-24T13:43:17.942+05:30  INFO 9080 --- [           main] c.e.S.SpringJpaTestApplication           : No active profile set, falling back to 1 default profile: "default"
2023-07-24T13:43:18.890+05:30  INFO 9080 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-07-24T13:43:18.928+05:30  INFO 9080 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 18 ms. Found 0 JPA repository interfaces.
2023-07-24T13:43:19.819+05:30  INFO 9080 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-07-24T13:43:19.838+05:30  INFO 9080 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-07-24T13:43:19.839+05:30  INFO 9080 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.10]
2023-07-24T13:43:20.020+05:30  INFO 9080 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-07-24T13:43:20.026+05:30  INFO 9080 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1913 ms
2023-07-24T13:43:20.246+05:30  INFO 9080 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-07-24T13:43:20.814+05:30  INFO 9080 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@c3719e5
2023-07-24T13:43:20.818+05:30  INFO 9080 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2023-07-24T13:43:20.877+05:30  INFO 9080 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2023-07-24T13:43:20.987+05:30  INFO 9080 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 6.2.5.Final
2023-07-24T13:43:20.992+05:30  INFO 9080 --- [           main] org.hibernate.cfg.Environment            : HHH000406: Using bytecode reflection optimizer
2023-07-24T13:43:21.124+05:30  INFO 9080 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2023-07-24T13:43:21.341+05:30  INFO 9080 --- [           main] o.h.b.i.BytecodeProviderInitiator        : HHH000021: Bytecode provider name : bytebuddy
2023-07-24T13:43:21.602+05:30  INFO 9080 --- [           main] o.s.o.j.p.SpringPersistenceUnitInfo      : No LoadTimeWeaver setup: ignoring JPA class transformer
2023-07-24T13:43:21.685+05:30  WARN 9080 --- [           main] org.hibernate.orm.deprecation            : HHH90000026: MySQL8Dialect has been deprecated; use org.hibernate.dialect.MySQLDialect instead
2023-07-24T13:43:21.810+05:30  INFO 9080 --- [           main] o.h.b.i.BytecodeProviderInitiator        : HHH000021: Bytecode provider name : bytebuddy
2023-07-24T13:43:22.082+05:30  INFO 9080 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-07-24T13:43:22.090+05:30  INFO 9080 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2023-07-24T13:43:22.154+05:30  WARN 9080 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2023-07-24T13:43:22.650+05:30  INFO 9080 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-07-24T13:43:22.666+05:30  INFO 9080 --- [           main] c.e.S.SpringJpaTestApplication           : Started SpringJpaTestApplication in 5.202 seconds (process running for 6.165)

I am using same code but still not able to create a table.

Please find below logs

. ____ _ __ _ _
/\ / ' __ _ () __ __ _ \ \ \
( ( )_
_ | '_ | '| | ' / ` | \ \ \
\/ __)| |)| | | | | || (
| | ) ) ) )
' || .__|| ||| |_, | / / / /
=========|
|==============|
/=////
:: Spring Boot :: (v3.1.1)

2023-07-24T13:43:17.936+05:30  INFO 9080 --- [           main] c.e.S.SpringJpaTestApplication           : Starting SpringJpaTestApplication using Java 17.0.7 with PID 9080 (C:\Users\arpit.verma\Downloads\SpringJPATest\SpringJPATest\target\classes started by arpit.verma in C:\Users\arpit.verma\Downloads\SpringJPATest\SpringJPATest)
2023-07-24T13:43:17.942+05:30  INFO 9080 --- [           main] c.e.S.SpringJpaTestApplication           : No active profile set, falling back to 1 default profile: "default"
2023-07-24T13:43:18.890+05:30  INFO 9080 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-07-24T13:43:18.928+05:30  INFO 9080 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 18 ms. Found 0 JPA repository interfaces.
2023-07-24T13:43:19.819+05:30  INFO 9080 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-07-24T13:43:19.838+05:30  INFO 9080 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-07-24T13:43:19.839+05:30  INFO 9080 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.10]
2023-07-24T13:43:20.020+05:30  INFO 9080 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-07-24T13:43:20.026+05:30  INFO 9080 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1913 ms
2023-07-24T13:43:20.246+05:30  INFO 9080 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-07-24T13:43:20.814+05:30  INFO 9080 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@c3719e5
2023-07-24T13:43:20.818+05:30  INFO 9080 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2023-07-24T13:43:20.877+05:30  INFO 9080 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2023-07-24T13:43:20.987+05:30  INFO 9080 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 6.2.5.Final
2023-07-24T13:43:20.992+05:30  INFO 9080 --- [           main] org.hibernate.cfg.Environment            : HHH000406: Using bytecode reflection optimizer
2023-07-24T13:43:21.124+05:30  INFO 9080 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2023-07-24T13:43:21.341+05:30  INFO 9080 --- [           main] o.h.b.i.BytecodeProviderInitiator        : HHH000021: Bytecode provider name : bytebuddy
2023-07-24T13:43:21.602+05:30  INFO 9080 --- [           main] o.s.o.j.p.SpringPersistenceUnitInfo      : No LoadTimeWeaver setup: ignoring JPA class transformer
2023-07-24T13:43:21.685+05:30  WARN 9080 --- [           main] org.hibernate.orm.deprecation            : HHH90000026: MySQL8Dialect has been deprecated; use org.hibernate.dialect.MySQLDialect instead
2023-07-24T13:43:21.810+05:30  INFO 9080 --- [           main] o.h.b.i.BytecodeProviderInitiator        : HHH000021: Bytecode provider name : bytebuddy
2023-07-24T13:43:22.082+05:30  INFO 9080 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-07-24T13:43:22.090+05:30  INFO 9080 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2023-07-24T13:43:22.154+05:30  WARN 9080 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2023-07-24T13:43:22.650+05:30  INFO 9080 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-07-24T13:43:22.666+05:30  INFO 9080 --- [           main] c.e.S.SpringJpaTestApplication           : Started SpringJpaTestApplication in 5.202 seconds (process running for 6.165)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文