1
請幫我解決這個問題。我有一個Hibernate的彈簧MVC項目, 和「src/main/resources /」目錄下的db.sql文件。如何在運行應用程序時在db.sql文件中執行腳本? 這是我的db.sql文件腳本。Spring MVC,運行時如何從src/main/resources目錄讀取.sql文件?
CREATE DATABASE IF NOT EXISTS `accounts`;
USE `accounts`;
--
-- Table structure for table `role`
--
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;
--
-- Dumping data for table `role`
--
LOCK TABLES `role` WRITE;
INSERT INTO `role` VALUES (1, 'ROLE_USER');
UNLOCK TABLES;
--
-- Table structure for table `user`
--
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;
--
-- 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;
我讀到這一些帖子,我發現有用的結果,例如這一個
Resource resource = applicationContext.getResource("classpath:db.sql");
InputStream is = resource.getInputStream();
但我不知道如何在我的程序的啓動執行代碼此兩行。 把它放在哪裏。
檢查此問題,它與您的需求有關:https://stackoverflow.com/questions/32838100/spring-hibernate-mysql-initialization – Dez