Spring Boot 整合持久層之JdbcTemplate
整合JdbcTemplate
JdbcTemplate 是 Spring 提供的一套 JDBC 模板框架,利用 AOP 技術(shù)來解決直接使用 JDBC 時大量重復(fù)代碼的問題。JdbcTemplate 雖然沒有 Mybatis 靈活,但是比直接使用 JDBC 方便很多。Spring Boot 中對 JdbcTemplate 的使用提供了自動化配置類 JdbcTemplateAutoConfiguration,部分源碼如下:
@Configuration
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
@EnableConfigurationProperties({JdbcProperties.class})
public class JdbcTemplateAutoConfiguration {
public JdbcTemplateAutoConfiguration() {
}
@Configuration
@Import({JdbcTemplateAutoConfiguration.JdbcTemplateConfiguration.class})
static class NamedParameterJdbcTemplateConfiguration {
NamedParameterJdbcTemplateConfiguration() {
}
@Bean
@Primary
@ConditionalOnSingleCandidate(JdbcTemplate.class)
@ConditionalOnMissingBean({NamedParameterJdbcOperations.class})
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcTemplate jdbcTemplate) {
return new NamedParameterJdbcTemplate(jdbcTemplate);
}
}
@Configuration
static class JdbcTemplateConfiguration {
private final DataSource dataSource;
private final JdbcProperties properties;
JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {
this.dataSource = dataSource;
this.properties = properties;
}
@Bean
@Primary
@ConditionalOnMissingBean({JdbcOperations.class})
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
Template template = this.properties.getTemplate();
jdbcTemplate.setFetchSize(template.getFetchSize());
jdbcTemplate.setMaxRows(template.getMaxRows());
if (template.getQueryTimeout() != null) {
jdbcTemplate.setQueryTimeout((int)template.getQueryTimeout().getSeconds());
}
return jdbcTemplate;
}
}
}從源碼中看出,當 classpath 下存在 DataSource 和 JdbcTemplate 并且 DataSource 只有一個實例時,自動配置才會生效,若開發(fā)者沒有提供 JdbcOperations ,則 Spring Boot 會自動向容器中注入一個 JdbcTemplate (JdbcTemplate 是 JdbcOperations 的子類)。因此,開發(fā)者想使用 JdbcTemplate 只需要提供 JdbcTemplate 的依賴和 DataSource 依賴即可
創(chuàng)建數(shù)據(jù)庫和表
在數(shù)據(jù)庫中創(chuàng)建表,如下:
CREATE TABLE `book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(128) DEFAULT NULL, `author` varchar(128) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO `chapter05`(`id`, `name`, `author`) VALUES (1, '斗羅大陸Ⅰ', '唐家三少'); INSERT INTO `chapter05`(`id`, `name`, `author`) VALUES (2, '斗羅大陸Ⅱ', '唐家三少');
創(chuàng)建項目
創(chuàng)建 Spring Boot 項目 ,添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency>
spring-boot-starter-jdbc 中提供了 spring-jdbc,另外還加入了數(shù)據(jù)庫驅(qū)動依賴和數(shù)據(jù)庫連接池依賴
數(shù)據(jù)庫配置
在application.properties 中配置數(shù)據(jù)庫基本連接信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/weirdo
spring.datasource.username=root
spring.datasource.password=root
創(chuàng)建實體類
創(chuàng)建 Book 實體類,代碼如下:
public class Book {
private int id;
private String name;
private String author;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}創(chuàng)建數(shù)據(jù)庫訪問層
創(chuàng)建 BookDao,代碼如下:
@Repository
public class BookDao {
@Autowired
JdbcTemplate jdbcTemplate;
public int addBook(Book book) {
return jdbcTemplate.update("INSERT INTO book(name,author) VALUES (?,?)",
book.getName(), book.getAuthor());
}
public int updateBook(Book book) {
return jdbcTemplate.update("UPDATE book SET name=?,author=? WHERE id=?",
book.getName(), book.getAuthor(), book.getId());
}
public int deleteBookById(Integer id) {
return jdbcTemplate.update("DELETE FROM book WHERE id=?", id);
}
public Book getBookById(Integer id) {
return jdbcTemplate.queryForObject("select * from book where id=?",
new BeanPropertyRowMapper<>(Book.class), id);
}
public List<Book> getAllBooks() {
return jdbcTemplate.query("select * from book",
new BeanPropertyRowMapper<>(Book.class));
}
}代碼解釋:
- 創(chuàng)建 BookDao ,注入 jdbcTemplate 。由于已經(jīng)添加了 spring-jdbc 相關(guān)依賴, JdbcTemplate 會被自動注冊到 Spring 容器中,因此這里可以直接注入 JdbcTemplate 使用
- 在 JdbcTemplate 中,增刪改三種類型的操作主要使用 update 和 batchUpdate 方法來完成,query 和 queryForObject 方法主要用來完成查詢功能。另外,還有 execute 方法可以用來執(zhí)行任意的sql、call 方法用來調(diào)用存儲過程等
- 在執(zhí)行查詢操作時,需要有一個 RowMapper 將查詢出來的列和實體類中的屬性一一對應(yīng)。如果列名和屬性名是相同的,那么可以直接使用 BeanPropertyRowMapper;如果列名和屬性名不同,需要開發(fā)者自己實現(xiàn) RowMapper 接口,將列和實體類屬性一一對應(yīng)起來
創(chuàng)建 Service 和 Controller
創(chuàng)建 BookService 和 BooKController
@Service
public class BookService {
@Autowired
BookDao bookDao;
public int addBook(Book book) {
return bookDao.addBook(book);
}
public int updateBook(Book book) {
return bookDao.updateBook(book);
}
public int deleteBookById(Integer id) {
return bookDao.deleteBookById(id);
}
public Book getBookById(Integer id) {
return bookDao.getBookById(id);
}
public List<Book> getAllBooks() {
return bookDao.getAllBooks();
}
}
@RestController
public class BookController {
@Autowired
BookService bookService;
@GetMapping("/bookOps")
public void bookOps() {
Book b1 = new Book();
b1.setId(99);
b1.setName("西廂記");
b1.setAuthor("王實甫");
int i = bookService.addBook(b1);
System.out.println("addBook>>>" + i);
Book b2 = new Book();
b2.setId(1);
b2.setName("朝花夕拾");
b2.setAuthor("魯迅");
int updateBook = bookService.updateBook(b2);
System.out.println("updateBook>>>"+updateBook);
Book b3 = bookService.getBookById(1);
System.out.println("getBookById>>>"+b3);
int delete = bookService.deleteBookById(2);
System.out.println("deleteBookById>>>"+delete);
List<Book> allBooks = bookService.getAllBooks();
System.out.println("getAllBooks>>>"+allBooks);
}
}
最后在瀏覽器中訪問 http://localhost:8081/bookOps 地址,控制臺打印日志如下:
addBook>>>1
updateBook>>>1
getBookById>>>com.sang.Book@35e33288
deleteBookById>>>1
getAllBooks>>>[com.sang.Book@2f7c2d6d, com.sang.Book@32db4b36]
數(shù)據(jù)庫中的數(shù)據(jù)如下:

到此這篇關(guān)于Spring Boot 整合持久層之JdbcTemplate的文章就介紹到這了,更多相關(guān)Spring Boot JdbcTemplate內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring?Boot整合持久層之JdbcTemplate多數(shù)據(jù)源
- SpringBoot2使用JTA組件實現(xiàn)基于JdbcTemplate多數(shù)據(jù)源事務(wù)管理(親測好用)
- 詳解SpringBoot中JdbcTemplate的事務(wù)控制
- 詳解Springboot之整合JDBCTemplate配置多數(shù)據(jù)源
- SpringBoot多數(shù)據(jù)源配置詳細教程(JdbcTemplate、mybatis)
- SpringBoot使用JdbcTemplate操作數(shù)據(jù)庫
- 詳解spring boot中使用JdbcTemplate
- Spring Boot中的JdbcTemplate是什么及用法小結(jié)
相關(guān)文章
grade構(gòu)建閱讀spring源碼環(huán)境 Idea2020.3的過程
這篇文章主要介紹了grade構(gòu)建閱讀spring源碼環(huán)境 Idea2020.3,本文分步驟通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
springBoot集成Elasticsearch 報錯 Health check failed的解決
這篇文章主要介紹了springBoot集成Elasticsearch 報錯 Health check failed的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Eclipse中查看android工程代碼出現(xiàn)"android.jar has no source attachment
這篇文章主要介紹了Eclipse中查看android工程代碼出現(xiàn)"android.jar has no source attachment"的解決方案,需要的朋友可以參考下2016-05-05
Java實現(xiàn)拖拽文件上傳dropzone.js的簡單使用示例代碼
本篇文章主要介紹了Java實現(xiàn)拖拽文件上傳dropzone.js的簡單使用示例代碼,具有一定的參考價值,有興趣的可以了解一下2017-07-07

