spring boot配置mysql

spring boot通过简单的配置就可以连接mysql,并且可以创建默认的连接池HikariDataSource,下面我们来看一看如何配置mysql

  1. 添加maven依赖,代码如下
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
  1. 修改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

  1. 添加测试代码,在启动方法中添加如下代码,用JdbcTemplate操作数据库
@SpringBootApplication
public 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);
         }

}

你可能感兴趣的:(数据库,Spring,mysql,spring,boot,java)