【问题标题】:No way of loading data.sql resource file on startup启动时无法加载 data.sql 资源文件
【发布时间】:2018-04-24 21:56:07
【问题描述】:

我正在开发一个 spring mvc 和 jpa 应用程序,我需要一种在应用程序运行时加载 data.sql 文件的方法。我用了这个方法,但是不行。

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

但它不会加载资源,因为数据库不是在应用程序运行后创建的。 这是我的 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;

请为我提供正确的方法。 或者没有办法一开始就加载任何资源文件。

【问题讨论】:

  • 如果您的 SQL 文件位于测试资源目录中,您可能应该将 FileSystemResourceLoader 替换为 DefaultResourceLoader 并使用 classpath:data.sql 作为 getResource(...) 方法的输入。我们还需要在返回 EMF 之前显式调用entityManagerFactoryBean.afterPropertiesSet(),尽管我们通常指定它(和事务管理器)有点不同。由于我们只需要导入我们的表定义,因此我不能 100% 确定创建数据库是否也能以这种方式工作。

标签: java mysql spring-mvc jpa


【解决方案1】:

我认为您错误地使用了 ResourceLoader。

看看这个

ResourceLoader documentation & examples

如果文件 data.sql 存在于类路径中,请使用示例 3,如果它在您的文件系统中,请使用示例 1。

希望这会有所帮助。

【讨论】:

  • 那么任何人都可以告诉我在 jpa 中使用资源加载器的正确方法吗?
  • 老兄,你没有看到我在回复中发布的链接吗??
  • offcoure 我看到了,但是您没有在 jpa 中指定方式,在 "LocalContainerEntityManagerFactoryBean" 中。我问了那个解决方案。但是您在示例中展示的其他方式对我来说很熟悉。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
  • 2014-10-11
  • 2020-09-29
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2011-02-25
相关资源
最近更新 更多