Java 无法让 spring boot 自动创建数据库架构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26881739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:27:40  来源:igfitidea点击:

Unable to get spring boot to automatically create database schema

javamysqlspringhibernatespring-boot

提问by napentathol

I'm unable to get spring boot to automatically load my database schema when I start it up.

当我启动它时,我无法让 spring boot 自动加载我的数据库架构。

Here is my application.properties:

这是我的 application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=test
spring.datasource.password=
spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.jpa.database = MYSQL

spring.jpa.show-sql = true

spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy

Here is my Application.java:

这是我的 Application.java:

@EnableAutoConfiguration
@ComponentScan
public class Application {
    public static void main(final String[] args){
        SpringApplication.run(Application.class, args);
    }
}

Here is a sample entity:

这是一个示例实体:

@Entity
@Table(name = "survey")
public class Survey implements Serializable {

    private Long _id;

    private String _name;

    private List<Question> _questions;

    /**
     * @return survey's id.
     */
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "survey_id", unique = true, nullable = false)
    public Long getId() {
        return _id;
    }

    /**
     * @return the survey name.
     */
    @Column(name = "name")
    public String getName() {
        return _name;
    }


    /**
     * @return a list of survey questions.
     */
    @OneToMany(mappedBy = "survey")
    @OrderBy("id")
    public List<Question> getQuestions() {
        return _questions;
    }

    /**
     * @param id the id to set to.
     */
    public void setId(Long id) {
        _id = id;
    }

    /**
     * @param name the name for the question.
     */
    public void setName(final String name) {
        _name = name;
    }

    /**
     * @param questions list of questions to set.
     */
    public void setQuestions(List<Question> questions) {
        _questions = questions;
    }
}

Any ideas what I'm doing wrong?

任何想法我做错了什么?

采纳答案by borys86

There are several possible causes:

有几种可能的原因:

  1. Your entity classes are in the same or in a sub-package relative one where you have you class with @EnableAutoConfiguration.If not then your spring app does not see them and hence will not create anything in db
  2. Check your config, it seems that you are using some hibernate specific options, try to replace them with:

    spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
    spring.jpa.hibernate.ddl-auto=update
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=test
    spring.datasource.password=
    
  3. Your application.propertiesmust be in src/main/resourcesfolder.

  1. 您的实体类在同一个或相对的子包中,@EnableAutoConfiguration.如果没有,则您的 spring 应用程序看不到它们,因此不会在 db 中创建任何内容
  2. 检查您的配置,似乎您正在使用一些休眠特定选项,请尝试将它们替换为:

    spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
    spring.jpa.hibernate.ddl-auto=update
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=test
    spring.datasource.password=
    
  3. application.properties必须在src/main/resources文件夹中。

If you did not specify dialect correctly it might try to default to bundled together with boot in-memory database and (as it was with me) I could see that it tries to connect to local HSQL(see console output) instance and fail at updating the schema.

如果您没有正确指定方言,它可能会尝试默认与引导内存数据库捆绑在一起,并且(就像我一样)我可以看到它尝试连接到本地HSQL(请参阅控制台输出)实例并且无法更新架构。

回答by liorsolomon

Did you try running it with:

您是否尝试使用以下命令运行它:

spring.jpa.generate-ddl=true

and then

进而

spring.jpa.hibernate.ddl-auto = create

By default the DDL execution (or validation) is deferred until the ApplicationContext has started. There is also a spring.jpa.generate-ddl flag, but it is not used if Hibernate autoconfig is active because the ddl-auto settings are more fine-grained.

默认情况下,DDL 执行(或验证)被推迟到 ApplicationContext 启动。还有一个 spring.jpa.generate-ddl 标志,但如果 Hibernate autoconfig 处于活动状态,则不会使用它,因为 ddl-auto 设置更细粒度。

see spring-boot-features

spring-boot-features

回答by user3206144

I also have the same problem. Turned out I have the @PropertySource annotation set on the main Application class to read a different base properties file, so the normal "application.properties" is not used anymore.

我也有同样的问题。结果我在主 Application 类上设置了 @PropertySource 注释以读取不同的基本属性文件,因此不再使用正常的“application.properties”。

回答by djuka

I had same problem and solved it with only this add:

我有同样的问题,只用这个添加解决了它:

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

回答by erickbhrener

If your entity class isn't in the same package as your main class, you can use @EntityScanannotation in the main class, specifying the Entity you want to save or package too. Like your model package.

如果您的实体类与您的主类不在同一个包中,您可以@EntityScan在主类中使用注解,指定要保存或打包的实体。喜欢你的模型包。

About:

关于:

spring.jpa.hibernate.ddl-auto = create

You can use the option update. It won't erase any data, and will create tables in the same way.

您可以使用该选项update。它不会删除任何数据,并且会以相同的方式创建表。

回答by Saurabh Agrawal

Just add

只需添加

spring.jpa.databaseplatform=org.hibernate.dialect.PostgreSQLDialect  

at the end. This will solve your issue. Only this was missing

在末尾。这将解决您的问题。只缺少这个

回答by Ar maj

@SpringBootApplication
@EnableConfigurationProperties
@EntityScan(basePackages = {"com.project.ppaa.model"})  // scan JPA entities
public class Application {

  private static ConfigurableApplicationContext applicationContext;

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

it should work automatically but if it does not, you can enter the base package

它应该自动工作,但如果没有,您可以输入基础包

@EntityScan(basePackages = {"com.project.ppaa.model"})  // scan JPA entities manually

回答by Usman Yaqoob

Use this Sample code

application.properties
# DataSource settings: set here your own configurations for the database 
# connection. In this example we have "dojsb" as database name and 
# "root" as username and password.
spring.datasource.url =jdbc:postgresql://localhost:5432/usman
spring.datasource.username = postgres
spring.datasource.password = 12345

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = create

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

server.port = 8963



Entity Class:



import java.sql.Timestamp;
import java.util.UUID;

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

import org.hibernate.annotations.Type;


@Entity
@Table(name = "QUEUERECORDS")
public class QueuesRecords {
    @Id
    private UUID id;

    @Column(name="payload", nullable = true)
    @Type(type="text")
    private String payload;


    @Column(name="status", nullable = true)
    @Type(type="text")
    private String status;

    private Timestamp starttime;

    private Timestamp endtime;

    @Column(name="queueid",nullable= true)
    @Type(type="text")
    private String queueid;

    public UUID getId() {
        return id;
    }

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

    public String getPayload() {
        return payload;
    }

    public void setPayload(String payload) {
        this.payload = payload;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Timestamp getStarttime() {
        return starttime;
    }

    public void setStarttime(Timestamp starttime) {
        this.starttime = starttime;
    }

    public Timestamp getEndtime() {
        return endtime;
    }

    public void setEndtime(Timestamp endtime) {
        this.endtime = endtime;
    }

    public String getQueueid() {
        return queueid;
    }

    public void setQueueid(String queueid) {
        this.queueid = queueid;
    }



}



Main class



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class Test{

    public static void main(String[] args) {

        SpringApplication.run(Test.class, args);


    }
}

回答by lamarre

I had the same problem before. My problem was the Entity relationship I was trying to establish by using a "List". I knew it was the cause because the program ran fine without the list variable. In your case, I think the problem is:

我以前也遇到过同样的问题。我的问题是我试图通过使用“列表”建立的实体关系。我知道这是原因,因为程序在没有列表变量的情况下运行良好。在你的情况下,我认为问题是:

private List<Question> _questions;

I am assuming you already have a class named Question. So, try having:

我假设您已经有一个名为 Question 的类。所以,尝试:

@OneToMany
private Question _questions;

But the thing is, in your method, you are going to handle it so it return a list. I used Spring Data JPA with CrudRepository. So, if you decide to use it, yours may look like this:

但问题是,在您的方法中,您将处理它以便它返回一个列表。我将 Spring Data JPA 与 CrudRepository 一起使用。所以,如果你决定使用它,你的可能看起来像这样:

public List<Question> findById( Long _id );

There are more changes you will have to do, but these are pretty easy and straightforward. Refer to this Java Brains videoto have a better grasp and see what else needs to be modified.

您还需要进行更多更改,但这些更改非常简单明了。请参阅此 Java Brains 视频以更好地掌握并查看还需要修改的内容。

回答by Jayant Nayak

In my case the tables were not getting created automatically even though I was using JPArepository. After adding the below property in my springboot app application.properties file the tables are now getting created automatically. spring.jpa.hibernate.ddl-auto=update

在我的情况下,即使我使用的是 JPArepository,表也不会自动创建。在我的 springboot 应用程序 application.properties 文件中添加以下属性后,表格现在会自动创建。 spring.jpa.hibernate.ddl-auto=更新