简体   繁体   English

无法在启动时加载data.sql资源文件

[英]No way of loading data.sql resource file on startup

Im am developing a spring mvc and jpa application, and I need a way of loading data.sql file when app runs. 我正在开发一个Spring MVC和JPA应用程序,我需要一种在应用程序运行时加载data.sql文件的方法。 I used this method, but it does not work. 我使用了这种方法,但是它不起作用。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.egs.account.repository"})
@PropertySource(value = { "classpath:application.properties" })
public class JpaConfig {

    @Autowired
    private Environment env;

    @Bean(name = "entityManagerFactory")
    LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
                new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("com.egs.account.model");

        final ResourceLoader resourceLoader = new FileSystemResourceLoader();
        resourceLoader.getResource("/data.sql");
        entityManagerFactoryBean.setResourceLoader(resourceLoader);
        final Properties jpaProperties = new Properties();
        jpaProperties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
        jpaProperties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        jpaProperties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
//        jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));

        return dataSource;
    }

    @Bean
    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource);
        initializer.setDatabasePopulator(databasePopulator());
        return initializer;
    }

    @Bean
    public DatabasePopulator databasePopulator() {
        ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
        databasePopulator.addScript(new ClassPathResource("classpath:/data.sql", JpaConfig.class));
        return databasePopulator;
    }

    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
}

But it does not load the resource, since the database is not created after app runs. 但它不会加载资源,因为在应用程序运行后不会创建数据库。 this is my sql script file. 这是我的sql脚本文件。

CREATE DATABASE IF NOT EXISTS `accounts`;
USE `accounts`;

--
-- Table structure for table `user`
--
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id`             INT(11) NOT NULL AUTO_INCREMENT,
  `username`       VARCHAR(255)     DEFAULT NULL,
  `password`       VARCHAR(255)     DEFAULT NULL,
  `firstName`      VARCHAR(255)     DEFAULT NULL,
  `lastName`       VARCHAR(255)     DEFAULT NULL,
  `email`          VARCHAR(255)     DEFAULT NULL,
  `dateRegistered` DATE             DEFAULT NULL,
  `skypeID`        VARCHAR(255)     DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 4
  DEFAULT CHARSET = utf8;
SET FOREIGN_KEY_CHECKS = 1;

--
-- Table structure for table `role`
--

SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `id`   INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45)      DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 2
  DEFAULT CHARSET = utf8;
SET FOREIGN_KEY_CHECKS = 1;
--
-- Dumping data for table `role`
--

LOCK TABLES `role` WRITE;
INSERT INTO `role` VALUES (1, 'ROLE_USER');
UNLOCK TABLES;

--
-- Table structure for table `user_role`
--

DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `user_id` INT(11) NOT NULL,
  `role_id` INT(11) NOT NULL,
  PRIMARY KEY (`user_id`, `role_id`),
  KEY `fk_user_role_roleid_idx` (`role_id`),
  CONSTRAINT `fk_user_role_roleid` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_user_role_userid` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;


DROP TABLE IF EXISTS `catalog`;
CREATE TABLE catalog (
  `id`         INT(11)      NOT NULL AUTO_INCREMENT,
  `user_id`    INT(11)      NOT NULL,
  `link`       VARCHAR(100) NOT NULL,
  `comment`    VARCHAR(100) NOT NULL,
  `type`       VARCHAR(100) NOT NULL,
  `insertDate` DATE                  DEFAULT NULL,
  `content`    LONGBLOB     NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

Please provide me a proper way of doing this. 请为我提供执行此操作的正确方法。 or there is no way of initially loading any resource file. 或无法初始加载任何资源文件。

I think you are using the ResourceLoader incorrectly. 我认为您使用的ResourceLoader错误。

check this out 看一下这个

ResourceLoader documentation & examples ResourceLoader文档和示例

If the file data.sql is present in the classpath use example 3, if its in your file system use example 1. 如果类路径中存在文件data.sql,请使用示例3;如果文件系统中存在data.sql文件,请使用示例1。

hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM