環境idea2019.2のjdk1.8データベースのMySQL 5.7
プロジェクト構造
新しい - SDKの次の選択springbootの迅速ビルドWebプロジェクトを使用して>プロジェクト
情報次のプロジェクトに記入
ポイントのWeb - >春のWebをチェック
ポイントSQL-> JDBC APIおよびMySQLのドライバをチェック
最終的なプロジェクト情報を確認し、この例では、単に最終テーブルにはデータの生成の例を有する生成見るために開くように完了あまりに膨大な点を
春: データソース: ドライバー - クラス - 名:com.mysql.cj.jdbc.Driverの URLます。jdbc:mysqlの:// localhostを:3306 / JDBC useSslオプション=真&serverTimezone = UTC&characterEncoding = UTF8? データ- ユーザ名:ルート データ - パスワード:ルート 初期化 - モード:常に スキーマ =クラスパス:schema.sql
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;
测试数据库连接
@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
生成表并且插入数据
完整的项目结构