Spring boot 连接MySQL,使用数据源hikaricp

1 .添加依赖
 
      org.springframework.boot
      spring-boot-starter-jdbc
  


  mysql
  mysql-connector-java
  6.0.5

spring-boot-starter-jdbc带来两个jar包:

  com.zaxxer
  HikariCP
  2.7.9
  compile


  org.springframework
  spring-jdbc
  5.0.7.RELEASE
  compile

mysql-connector-java 数据库驱动

2.增加MySQL配置信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.min-idle=5


3.增加数据源配置类 DataSourceConfig
common\config\DataSourceConfig.java

@Configuration
public class DataSourceConfig {
   
   
   @Bean(name="dataSource")
   public DataSource datasource(Environment env) {
      HikariDataSource ds = new HikariDataSource();
      ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
      ds.setUsername(env.getProperty("spring.datasource.username"));
      ds.setPassword(env.getProperty("spring.datasource.password"));
      ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
      ds.setMaximumPoolSize(Integer.parseInt(env.getProperty("spring.datasource.max-idle")));
      ds.setMinimumIdle(Integer.parseInt(env.getProperty("spring.datasource.min-idle")));
      return ds;
   }
}

3.测试JdbcTemplate
@Controller
public class LoginController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("toLogin")
    public String loginIndex(){
        int count = jdbcTemplate.queryForObject("select count(1) from user",Integer.class);
        System.out.println(count);
        return "admin/login";
    }


}




你可能感兴趣的:(java,Spring,Spring,boot)