Hibernate + Spring Boot + PostgreSQL在启动时不自动创建表,没有错误。

huangapple go评论65阅读模式
英文:

Hibernate + Spring boot + PostgreSQL not auto Creating table on startup, no errors

问题

我已经开始学习Springboot,但在启动应用程序时遇到了一个问题,Hibernate没有根据我的实体创建表。我正在使用Postgres作为SQL数据库。

我也包含了迄今为止尝试排除故障的步骤。应用程序启动了,但没有创建我的表。

在启动时我没有收到任何错误。

实体类

@Entity
@Table
public class Student {
    // ... (你的实体类代码)
}

主应用程序类

@SpringBootApplication
public class SpringbootApplication {
    // ... (你的主应用程序类代码)
}

控制器

@RestController
@RequestMapping(path = "api/v1/student")
public class StudentController {
    // ... (你的控制器类代码)
}

服务

@Service
public class StudentService {
    // ... (你的服务类代码)
}

application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/student
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true

pom.xml

<!-- 你的pom.xml文件内容 -->

控制台输出

// 你的控制台输出
  1. 我将spring.jpa.hibernate.ddl-autocreate-drop更改为create
  2. 我已确认在IDE中成功连接到我的数据库。
  3. 我更新了项目包的groupIdartifactId,从使用Spring initialzr构建项目时默认的值。
  4. 我已在Stack Overflow深入搜索,解决问题的所有建议似乎已经在我的代码/文件中了。
  5. application.properties文件中包含了logging.level.org.hibernate.SQL=DEBUG,但Hibernate没有输出任何日志。
英文:

I've started learning Springboot and I'm running into an issue when starting my application where Hibernate isn't creating a table from my entity. I'm using Postgres for SQL

I've also included the steps I have taken so far to try and troubleshoot. The application starts up, however it doesn't create my table

I'm not receiving any errors on startup.

Entity class

package com.example.springboot.student;

import javax.persistence.*;

import java.time.LocalDate;

@Entity
@Table
public class Student {
    @Id
    @SequenceGenerator(
            name = &quot;student_sequence&quot;,
            sequenceName = &quot;student_sequence&quot;,
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = &quot;student_sequence&quot;
    )
    private Long id;
    private String name;
    private String email;
    private LocalDate dob;
    private Integer age;

    public Student() {
    }

    public Student(Long id, String name, String email, LocalDate dob, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.dob = dob;
        this.age = age;
    }

    public Student(String name, String email, LocalDate dob, Integer age) {
        this.name = name;
        this.email = email;
        this.dob = dob;
        this.age = age;
    }

    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;
    }

    public LocalDate getDob() {
        return dob;
    }

    public void setDob(LocalDate dob) {
        this.dob = dob;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return &quot;Student{&quot; +
                &quot;id=&quot; + id +
                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +
                &quot;, email=&#39;&quot; + email + &#39;\&#39;&#39; +
                &quot;, dob=&quot; + dob +
                &quot;, age=&quot; + age +
                &#39;}&#39;;
    }
}

main application Class

package com.example.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootApplication.class, args);
	}

}

Controller

package com.example.springboot.student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(path = &quot;api/v1/student&quot;)
public class StudentController {

    private final StudentService studentService;

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public List&lt;Student&gt; getStudents() {
        return studentService.getStudents();
    }

}

Service

package com.example.springboot.student;

import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Month;
import java.util.List;

@Service
public class StudentService {

    public List&lt;Student&gt; getStudents() {
        return List.of(
                new Student(
                        1L,
                        &quot;Mariam&quot;,
                        &quot;mariam.jamal@gmail.com&quot;,
                        LocalDate.of(2000, Month.JANUARY, 5),
                        21)
        );
    }

}

application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/student
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true

pom.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;parent&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
		&lt;version&gt;2.7.9&lt;/version&gt;
		&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
	&lt;/parent&gt;
	&lt;groupId&gt;com.example&lt;/groupId&gt;
	&lt;artifactId&gt;springboot&lt;/artifactId&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;name&gt;springboot&lt;/name&gt;
	&lt;description&gt;Demo project for Spring Boot&lt;/description&gt;
	&lt;properties&gt;
		&lt;java.version&gt;11&lt;/java.version&gt;
	&lt;/properties&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-data-jdbc&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.postgresql&lt;/groupId&gt;
			&lt;artifactId&gt;postgresql&lt;/artifactId&gt;
			&lt;scope&gt;runtime&lt;/scope&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
			&lt;scope&gt;test&lt;/scope&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;javax.persistence&lt;/groupId&gt;
			&lt;artifactId&gt;javax.persistence-api&lt;/artifactId&gt;
			&lt;version&gt;2.2&lt;/version&gt;
			&lt;scope&gt;provided&lt;/scope&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
				&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;
    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;clojars&lt;/id&gt;
            &lt;name&gt;Clojars&lt;/name&gt;
            &lt;url&gt;https://repo.clojars.org/&lt;/url&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;

&lt;/project&gt;

Console

  .   ____          _            __ _ _
 /\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  &#39;  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.9)

2023-03-09 06:30:19.292  INFO 14164 --- [           main] c.e.springboot.SpringbootApplication     : Starting SpringbootApplication using Java 11.0.17 on DESKTOP-RL97UQV with PID 14164 (D:\springboot\target\classes started by byoun in D:\springboot)
2023-03-09 06:30:19.294  INFO 14164 --- [           main] c.e.springboot.SpringbootApplication     : No active profile set, falling back to 1 default profile: &quot;default&quot;
2023-03-09 06:30:19.673  INFO 14164 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2023-03-09 06:30:19.679  INFO 14164 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 3 ms. Found 0 JDBC repository interfaces.
2023-03-09 06:30:19.962  INFO 14164 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-03-09 06:30:19.968  INFO 14164 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-03-09 06:30:19.968  INFO 14164 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.71]
2023-03-09 06:30:20.047  INFO 14164 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-03-09 06:30:20.048  INFO 14164 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 717 ms
2023-03-09 06:30:20.318  INFO 14164 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-03-09 06:30:20.428  INFO 14164 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2023-03-09 06:30:20.514  INFO 14164 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path &#39;&#39;
2023-03-09 06:30:20.524  INFO 14164 --- [           main] c.e.springboot.SpringbootApplication     : Started SpringbootApplication in 1.507 seconds (JVM running for 2.216)
  1. I changed my spring.jpa.hibernate.ddl-auto from create-drop to just create
  2. I've confirmed I have a successful connection to my DB from within my IDE
  3. I updated the groupId and artifactId for my project package from the default that came from building the project with Spring initialzr
  4. I have searched the depths of stack overflow and all of the recommendations to resolve issues appear to already be present in my code/files.
  5. Included logging.level.org.hibernate.SQL=DEBUG to application.properties file but no logging is output from Hibernate

答案1

得分: 1

请将以下设置添加到application.properties文件中:

spring.jpa.generate-ddl=true

还请修改pom.xml文件的相应部分,以使用JPA而不是JDBC。

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
&lt;/dependency&gt;
英文:

Please add this setting to application.properties:

spring.jpa.generate-ddl=true

Please also change the part of pom.xml for use of JPA instead of JDBC.

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
&lt;/dependency&gt;

huangapple
  • 本文由 发表于 2023年3月9日 20:48:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定