SpringBoot2.2.2 version automatically create a table

Environmental idea2019.2 jdk1.8 database mysql 5.7

Project structure

 

new -> Project using springboot quickly build web projects selected sdk next

Fill in the information next project

 Point Web -> Check the Spring Web  

Point SQL-> Check the JDBC API and MySQL Driver

 Confirm final project information Finish too voluminous point to open to see this example simply generates the final table has examples of data generation 

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jdbc?useSSL=true&serverTimezone=UTC&characterEncoding=UTF8
    data-username: root
    data-password: root
    initialization-mode: always
    schema=classpath: schema.sql
application.yml
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
schema.sql

测试数据库连接  

@RunWith(SpringRunner.class)手动添加  没有自动生成
@RunWith(SpringRunner.class)
@SpringBootTest
class Springboot06jdbcApplicationTests {
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println("------>>>"+dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println("=========>>>"+connection);
        connection.close();
    }

}

springboot 2 以后默认使用HikariDataSource 数据源  

使用Hikari连接池

 

 

 验证后  运行spingboot启动类即可

 

 结果 

 

如果想生成表  并生成数据   请看下面操作

user.sql

 drop table  if exists user;
 create table user (id bigint(20) not null auto_increment,
 username varchar(40) DEFAULT NULL,
 name varchar(20) DEFAULT NULL,
 age int(3) DEFAULT NULL,
 balance decimal(10,2) DEFAULT NULL,
 primary key(id))ENGINE=InnoDB DEFAULT CHARSET=utf8;

data.sql

insert into user (id, username, name, age, balance) values (1,'account1','张三', 20, 100.00);
insert into user (id, username, name, age, balance) values (2,'account2','李四', 28, 180.00);
insert into user (id, username, name, age, balance) values (3,'account3','王五', 32, 280.00);

 修改application.yml    

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jdbc?useSSL=true&serverTimezone=UTC&characterEncoding=UTF8
    data-username: root
    data-password: root
    initialization-mode: always
    #schema=classpath: schema.sql
    schema=classpath: user.sql
    data=classpath: data.sql

 生成表并且插入数据

完整的项目结构

Guess you like

Origin www.cnblogs.com/wf-zhang/p/12163577.html