Spring Boot使用單資料來源配置JdbcTemplate.md
阿新 • • 發佈:2018-12-06
- 在單資料來源的情況下,Spring Boot的配置非常簡單,只需要在application.properties檔案中配置連線引數即可。
- 資料來源配置
-
- 首先,為了連線資料庫需要引入jdbc支援,在pom.xml中引入如下配置:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
-
- 嵌入式資料庫支援
- 嵌入式資料庫通常用於開發和測試環境,不推薦用於生產環境。Spring Boot提供自動配置的嵌入式資料庫有H2、HSQL、Derby,你不需要提供任何連線配置就能使用。比如,我們可以在pom.xml中引入如下配置使用HSQL
<dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <scope>runtime</scope> </dependency>
-
- 連線生產資料來源
- 以MySQL資料庫為例,先引入MySQL連線的依賴包,在pom.xml中加入:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
- 在application.properties檔案中配置資料來源資訊:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
-
- 連線JNDI資料來源
- 當你將應用部署於應用伺服器上的時候想讓資料來源由應用伺服器管理,那麼可以使用如下配置方式引入JNDI資料來源——在application.properties檔案中新增如下配置資訊:
spring.datasource.jndi-name=java:jboss/datasources/customers
- 使用JdbcTemplate操作資料庫
- Spring的JdbcTemplate是自動配置的,你可以直接使用@Autowired來注入到你自己的bean中來使用。
通過JdbcTemplate實現UserService中定義的資料訪問操作:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void create(String name, Integer age) {
jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
}
@Override
public void deleteByName(String name) {
jdbcTemplate.update("delete from USER where NAME = ?", name);
}
@Override
public Integer getAllUsers() {
return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
}
@Override
public void deleteAllUsers() {
jdbcTemplate.update("delete from USER");
}
}
- 總結
在Spring Boot下訪問資料庫的配置依然秉承了框架的初衷:簡單。我們只需要在pom.xml中加入資料庫依賴,再到application.properties中配置連線資訊,不需要像Spring應用中建立JdbcTemplate的Bean,就可以直接在自己的物件中注入使用。