首页 > 解决方案 > 如何通过 Spring 初始化程序创建数据库和表?

问题描述

我的资源文件夹中有两个 .sql 文件:createTables.sql创建表和init.sql创建数据库。

这是我的pom.xml

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd">4.0.0

<groupId>group</groupId>
<artifactId>artifact</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
    <spring.framework>4.3.0.RELEASE</spring.framework>
    <postgres.version>42.1.4</postgres.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>${postgres.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.framework}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.framework}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.framework}</version>
    </dependency>
</dependencies>

<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:init.sql"/>
    <jdbc:script location="classpath:createTables.sql"/>
</jdbc:initialize-database>

并且AppConfig.class

@Configuration
@ComponentScan("com.foxminded")
@PropertySource("classpath:db.properties")
public class AppConfig {



@Autowired
Environment environment;

private final static String URL = "URL";
private final static String USER = "USER";
private final static String DRIVER = "DRIVER";
private final static String PASSWORD = "PASSWORD";



@Bean
DriverManagerDataSource dataSource() {
    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
    driverManagerDataSource.setUrl(environment.getProperty(URL));
    driverManagerDataSource.setUsername(environment.getProperty(USER));
    driverManagerDataSource.setPassword(environment.getProperty(PASSWORD));
    driverManagerDataSource.setDriverClassName(environment.getProperty(DRIVER));
    return driverManagerDataSource;
}

还有我的 Main.class :

公共类主要{

public static void main(String[] qrgs) {

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

}

A 在我的数据库中没有看到我在 sql 文件中指示的指定 URL 的任何表。

init.sql文件 :

DROP DATABASE IF EXISTS task11;
DROP USER IF EXISTS task11user;
CREATE DATABASE task11;
CREATE USER task11user WITH password 'pass';
GRANT ALL privileges ON DATABASE task11 TO task11user;

createTables.sql文件 :

DROP TABLE IF EXISTS groups;
CREATE TABLE groups
(
PRIMARY KEY (group_id),
group_id   SERIAL,
group_name VARCHAR(100)
student_id INT,
  FOREIGN KEY (student_id) REFERENCES students(student_id)
);

标签: javaspring

解决方案


推荐阅读