spring boot通过简单的配置就可以连接mysql,并且可以创建默认的连接池HikariDataSource,下面我们来看一看如何配置mysql
添加maven依赖,代码如下
<!-- mysql --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
修改application.properties配置文件,添加如下代码
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
添加测试代码,在启动方法中添加如下代码,用JdbcTemplate操作数据库
@SpringBootApplicationpublic class SpringBootMysqlApplication {public static void main(String[] args) {ConfigurableApplicationContext context =SpringApplication.run(SpringBootMysqlApplication.class, args);JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);List<Map<String, Object>> result =jdbcTemplate.queryForList("SELECT * FROM USER");System.out.println(result);}}