:)
依賴
- starter 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
-
這個start依賴的其他庫
這個庫依賴了HikariCP旬渠,這是個數(shù)據(jù)庫連接池
關(guān)于數(shù)據(jù)庫連接池
- 如果依賴?yán)锩娲嬖贖ikariCP 那就使用這個連接池
- 如果不存在 HikariCP 而 Tomcat pooling的DataSource可以用就使用這個
- 如果上面兩個都不可用則使用 DBCP2
配置數(shù)據(jù)鏈接信息
- 需要配置的信息有 driverclassname 耳璧,url 陋葡,username, password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
- 為什么這樣配置隔缀? 主要是根據(jù) org.springframework.boot.autoconfigure.jdbc.DataSourceProperties 這個類來的肋演,這個類有個注解 @ConfigurationProperties(prefix = "spring.datasource") 所以前綴都是spring.datasource域醇,后面的url password 之類的值是這個類的變量,當(dāng)然這個類的其他有set方法的變量也是可以這樣配置的
訪問數(shù)據(jù)庫
- 配置了鏈接信息之后spring boot 就會創(chuàng)建 DataSource 和 連接池弧械,所以我們直接將DataSource注入就可以使用了(如果使用 jdbc starter 則默認(rèn)是使用了連接池的)
@Autowired
private DataSource dataSource;
@RequestMapping("/user")
public List<User> showAllInfo() throws SQLException {
String sql = "select * from sys_user";
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
List<User> users = new ArrayList<>();
while(resultSet.next()){
String name = resultSet.getString("user_name");
String number = resultSet.getString("user_password");
User user = new User();
user.setName(name);
user.setNumber(number);
users.add(user);
}
return users;
}
控制臺報錯Establishing SSL connection without server's identity verification is not recommended八酒,這個是因為mysql要求ssl鏈接,將鏈接url改成jdbc:mysql://127.0.0.1:3306/test?useSSL=true
使用 JdbcTemplate 訪問數(shù)據(jù)庫刃唐,org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration 這個類里面注冊了兩個Bean羞迷,JdbcTemplate 和 NamedParameterJdbcTemplate。我們就可以在代碼中直接注入使用
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/")
public List<User> showProperInfo(){
String sql = "select * from sys_user";
List<User> query = jdbcTemplate.query(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setName(rs.getString("user_name"));
user.setNumber(rs.getString("user_password"));
return user;
}
});
return query;
}
配置自己的數(shù)據(jù)源
- 有些時候我們想用其他的數(shù)據(jù)連接池画饥,這個時候就需要自己配置了衔瓮,配置方法就是定義一個bean
@Configuration
public class DataSourceConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String user;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource dataSource(){
MysqlDataSource source = new MysqlDataSource();
source.setURL(url);
source.setPassword(password);
source.setUser(user);
return source;
}
}
?
End