原本地址:Spring Boot乾貨系列:(八)資料儲存篇-SQL關係型資料庫之JdbcTemplate的使用
部落格地址:tengj.top/
前言
前面幾章介紹了一些基礎,但都是靜態的,還不足以構建一個動態的應用。本篇開始就要介紹資料互動了,為了演示效果更加好,博主花了大把時間整合了一個後端模板框架,基於Bootstrap3的ACE模板,並實現了一個基本的增刪改查分頁功能。讓我們一起動手,學技術的同時,順便把我們的專案完善起來,這樣跟著博主學到最後,你就有了一個屬於自己的Spring Boot專案啦。
正文
本文介紹在Spring Boot基礎下配置資料來源和通過JdbcTemplate編寫資料訪問的示例。
新增依賴
這裡需要新增spring-boot-starter-jdbc依賴跟mysql依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>複製程式碼
資料來源配置
在src/main/resources/application.properties中配置資料來源資訊。
spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver複製程式碼
自定義資料來源
spring-boot-starter-jdbc 預設使用tomcat-jdbc資料來源,如果你想使用其他的資料來源,比如這裡使用了阿里巴巴的資料池管理,你應該額外新增以下依賴:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>複製程式碼
修改Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
private Environment env;
//destroy-method="close"的作用是當資料庫連線不使用的時候,就把該連線重新放到資料池中,方便下次使用呼叫.
@Bean(destroyMethod = "close")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));//使用者名稱
dataSource.setPassword(env.getProperty("spring.datasource.password"));//密碼
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setInitialSize(2);//初始化時建立物理連線的個數
dataSource.setMaxActive(20);//最大連線池數量
dataSource.setMinIdle(0);//最小連線池數量
dataSource.setMaxWait(60000);//獲取連線時最大等待時間,單位毫秒。
dataSource.setValidationQuery("SELECT 1");//用來檢測連線是否有效的sql
dataSource.setTestOnBorrow(false);//申請連線時執行validationQuery檢測連線是否有效
dataSource.setTestWhileIdle(true);//建議配置為true,不影響效能,並且保證安全性。
dataSource.setPoolPreparedStatements(false);//是否快取preparedStatement,也就是PSCache
return dataSource;
}
}複製程式碼
ok這樣就算自己配置了一個DataSource,Spring Boot會智慧地選擇我們自己配置的這個DataSource例項。
指令碼初始化
CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `spring`;
DROP TABLE IF EXISTS `learn_resource`;
CREATE TABLE `learn_resource` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`author` varchar(20) DEFAULT NULL COMMENT '作者',
`title` varchar(100) DEFAULT NULL COMMENT '描述',
`url` varchar(100) DEFAULT NULL COMMENT '地址連結',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1029 DEFAULT CHARSET=utf8;
insert into `learn_resource`(`id`,`author`,`title`,`url`) values (999,'官方SpriongBoot例子','官方SpriongBoot例子','https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples');
insert into `learn_resource`(`id`,`author`,`title`,`url`) values (1000,'龍果學院','Spring Boot 教程系列學習','http://www.roncoo.com/article/detail/124661');
insert into `learn_resource`(`id`,`author`,`title`,`url`) values (1001,'嘟嘟MD獨立部落格','Spring Boot乾貨系列','http://tengj.top/');
insert into `learn_resource`(`id`,`author`,`title`,`url`) values (1002,'後端程式設計嘟','Spring Boot視訊教程','http://www.toutiao.com/m1559096720023553/');複製程式碼
開始使用JdbcTemplate
Spring的JdbcTemplate是自動配置的,你可以直接使用@Autowired
來注入到你自己的bean中來使用。這裡博主做了一套基本的增刪改查操作。
實體物件
public class LearnResouce {
private Long id;
private String author;
private String title;
private String url;
// SET和GET方法
}複製程式碼
Controller層
@Controller
@RequestMapping("/learn")
public class LearnController {
@Autowired
private LearnService learnService;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("")
public String learn(){
return "learn-resource";
}
@RequestMapping(value = "/queryLeanList",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
@ResponseBody
public void queryLearnList(HttpServletRequest request ,HttpServletResponse response){
String page = request.getParameter("page"); // 取得當前頁數,注意這是jqgrid自身的引數
String rows = request.getParameter("rows"); // 取得每頁顯示行數,,注意這是jqgrid自身的引數
String author = request.getParameter("author");
String title = request.getParameter("title");
Map<String,Object> params = new HashMap<String,Object>();
params.put("page", page);
params.put("rows", rows);
params.put("author", author);
params.put("title", title);
Page pageObj =learnService.queryLearnResouceList(params);
List<Map<String, Object>> learnList=pageObj.getResultList();
JSONObject jo=new JSONObject();
jo.put("rows", learnList);
jo.put("total", pageObj.getTotalPages());
jo.put("records", pageObj.getTotalRows());
ServletUtil.createSuccessResponse(200, jo, response);
}
/**
* 新添教程
* @param request
* @param response
*/
@RequestMapping(value = "/add",method = RequestMethod.POST)
public void addLearn(HttpServletRequest request , HttpServletResponse response){
JSONObject result=new JSONObject();
String author = request.getParameter("author");
String title = request.getParameter("title");
String url = request.getParameter("url");
if(StringUtil.isNull(author)){
result.put("message","作者不能為空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(title)){
result.put("message","教程名稱不能為空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(url)){
result.put("message","地址不能為空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
LearnResouce learnResouce = new LearnResouce();
learnResouce.setAuthor(author);
learnResouce.setTitle(title);
learnResouce.setUrl(url);
int index=learnService.add(learnResouce);
System.out.println("結果="+index);
if(index>0){
result.put("message","教程資訊新增成功!");
result.put("flag",true);
}else{
result.put("message","教程資訊新增失敗!");
result.put("flag",false);
}
ServletUtil.createSuccessResponse(200, result, response);
}
/**
* 修改教程
* @param request
* @param response
*/
@RequestMapping(value = "/update",method = RequestMethod.POST)
public void updateLearn(HttpServletRequest request , HttpServletResponse response){
JSONObject result=new JSONObject();
String id = request.getParameter("id");
LearnResouce learnResouce=learnService.queryLearnResouceById(Long.valueOf(id));
String author = request.getParameter("author");
String title = request.getParameter("title");
String url = request.getParameter("url");
if(StringUtil.isNull(author)){
result.put("message","作者不能為空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(title)){
result.put("message","教程名稱不能為空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(url)){
result.put("message","地址不能為空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
learnResouce.setAuthor(author);
learnResouce.setTitle(title);
learnResouce.setUrl(url);
int index=learnService.update(learnResouce);
System.out.println("修改結果="+index);
if(index>0){
result.put("message","教程資訊修改成功!");
result.put("flag",true);
}else{
result.put("message","教程資訊修改失敗!");
result.put("flag",false);
}
ServletUtil.createSuccessResponse(200, result, response);
}
/**
* 刪除教程
* @param request
* @param response
*/
@RequestMapping(value="/delete",method = RequestMethod.POST)
@ResponseBody
public void deleteUser(HttpServletRequest request ,HttpServletResponse response){
String ids = request.getParameter("ids");
System.out.println("ids==="+ids);
JSONObject result = new JSONObject();
//刪除操作
int index = learnService.deleteByIds(ids);
if(index>0){
result.put("message","教程資訊刪除成功!");
result.put("flag",true);
}else{
result.put("message","教程資訊刪除失敗!");
result.put("flag",false);
}
ServletUtil.createSuccessResponse(200, result, response);
}
}複製程式碼
Service層
public interface LearnService {
int add(LearnResouce learnResouce);
int update(LearnResouce learnResouce);
int deleteByIds(String ids);
LearnResouce queryLearnResouceById(Long learnResouce);
Page queryLearnResouceList(Map<String,Object> params);
}複製程式碼
實現類
@Service
public class LearnServiceImpl implements LearnService {
@Autowired
LearnDao learnDao;
@Override
public int add(LearnResouce learnResouce) {
return this.learnDao.add(learnResouce);
}
@Override
public int update(LearnResouce learnResouce) {
return this.learnDao.update(learnResouce);
}
@Override
public int deleteByIds(String ids) {
return this.learnDao.deleteByIds(ids);
}
@Override
public LearnResouce queryLearnResouceById(Long id) {
return this.learnDao.queryLearnResouceById(id);
}
@Override
public Page queryLearnResouceList(Map<String,Object> params) {
return this.learnDao.queryLearnResouceList(params);
}
}複製程式碼
Dao層
public interface LearnDao {
int add(LearnResouce learnResouce);
int update(LearnResouce learnResouce);
int deleteByIds(String ids);
LearnResouce queryLearnResouceById(Long id);
Page queryLearnResouceList(Map<String,Object> params);
}複製程式碼
實現類,這裡注入我們需要的JdbcTemplate
@Repository
public class LearnDaoImpl implements LearnDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int add(LearnResouce learnResouce) {
return jdbcTemplate.update("insert into learn_resource(author, title,url) values(?, ?, ?)",learnResouce.getAuthor(),learnResouce.getTitle(),learnResouce.getUrl());
}
@Override
public int update(LearnResouce learnResouce) {
return jdbcTemplate.update("update learn_resource set author=?,title=?,url=? where id = ?",new Object[]{learnResouce.getAuthor(),learnResouce.getTitle(),learnResouce.getUrl(),learnResouce.getId()});
}
@Override
public int deleteByIds(String ids){
return jdbcTemplate.update("delete from learn_resource where id in("+ids+")");
}
@Override
public LearnResouce queryLearnResouceById(Long id) {
List<LearnResouce> list = jdbcTemplate.query("select * from learn_resource where id = ?", new Object[]{id}, new BeanPropertyRowMapper(LearnResouce.class));
if(null != list && list.size()>0){
LearnResouce learnResouce = list.get(0);
return learnResouce;
}else{
return null;
}
}
@Override
public Page queryLearnResouceList(Map<String,Object> params) {
StringBuffer sql =new StringBuffer();
sql.append("select * from learn_resource where 1=1");
if(!StringUtil.isNull((String)params.get("author"))){
sql.append(" and author like '%").append((String)params.get("author")).append("%'");
}
if(!StringUtil.isNull((String)params.get("title"))){
sql.append(" and title like '%").append((String)params.get("title")).append("%'");
}
Page page = new Page(sql.toString(), Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()), jdbcTemplate);
return page;
}
}複製程式碼
上面介紹的JdbcTemplate
只是最基本的幾個操作,更多其他資料訪問操作的使用請參考:JdbcTemplate API
到此為止,後端互動程式碼都寫好了,這裡博主整合的bootstrap模板就不展示了,各位可以自行下載本篇對應的原始碼跑起來看看,效果很棒咯,如下:
總結
SpringBoot下訪問資料庫還是很簡單的,只要新增依賴,然後在application.properties中配置連線資訊。下一篇博主將介紹下Spring Boot對mybatis的整合。
想要檢視更多Spring Boot乾貨教程,可前往:Spring Boot乾貨系列總綱
原始碼下載
( ̄︶ ̄)↗[相關示例完整程式碼]
想要ace模板原始碼的話,在博主公眾號回覆關鍵字:ace
一直覺得自己寫的不是技術,而是情懷,一篇篇文章是自己這一路走來的痕跡。靠專業技能的成功是最具可複製性的,希望我的這條路能讓你少走彎路,希望我能幫你抹去知識的蒙塵,希望我能幫你理清知識的脈絡,希望未來技術之巔上有你也有我!
訂閱博主微信公眾號:嘟爺java超神學堂(javaLearn)三大好處:
- 獲取最新博主部落格更新資訊,首發公眾號
- 獲取大量視訊,電子書,精品破解軟體資源
- 可以跟博主聊天,歡迎程式媛妹妹來撩我