Springboot集成jdbcTemplate過程解析
一 說明
實(shí)際工作中其實(shí)很少會用到j(luò)dbcTemplate去操作數(shù)據(jù)庫,因?yàn)槠涫褂梅绞讲皇呛莒`活,sql的拼接能力不強(qiáng);實(shí)際上jdbcTemplate是屬于spring自帶的數(shù)據(jù)層模板,在spring中可以說是比較失敗的一個(gè)案例,原因是當(dāng)代流行mybatis當(dāng)做持久層訪問數(shù)據(jù)庫,其優(yōu)越的sql拼接能力、動(dòng)態(tài)sql、半自動(dòng)化映射、和易于sql優(yōu)化的特性,深受廣大互聯(lián)網(wǎng)公司的喜愛,并且mybatis的市場占有率不斷的上升,hibernate的市場不斷縮水,可以說hibernate已經(jīng)這種強(qiáng)映射關(guān)系的持久層模型已經(jīng)走到互聯(lián)網(wǎng)時(shí)代的盡頭了。
本文寫jdbcTemplate只是當(dāng)作大家的一個(gè)入門學(xué)習(xí),可以說以后你很難用到這門技術(shù),所以不會深入研究,有興趣的朋友可以專欄我其他關(guān)于springboot的集成系列。本次演示使用jdk1.8,mysql5.6,springboot2.1。
二數(shù)據(jù)庫建表和實(shí)體
user表,里面有三個(gè)屬性 用戶id、 用戶名和電話號碼。
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用戶id', `name` varchar(255) DEFAULT NULL COMMENT '用戶名', `telephone` varchar(255) DEFAULT NULL COMMENT '用戶電話', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
user表對應(yīng)的實(shí)體:
/**
* @Author lsc
* @Description <p>pojo </p>
* @Date 2019/11/2 10:16
*/
public class User {
// id
private Long id;
// 姓名
private String name;
// 電話
private String telephone;
// 省略 set get
}
三 dao層
對于使用jdbcTemplate,我們的dao層需要接口定義crud操作方法,其實(shí)現(xiàn)類則進(jìn)行具體的sql操作,很多開發(fā)人員沒有這種解耦的思想,往往就直接在servic層操作sql,可以說沒有完整的一個(gè)知識體系,往往會造成后期維護(hù)困難,項(xiàng)目無法進(jìn)行下去;
3.1 dao接口
/**
* @Author lsc
* @Description <p> user dao 接口 </p>
* @Date 2019/11/2 10:19
*/
public interface UserDao {
// 添加
int addUser(User user);
// 改
int updateUser(User user);
// 刪
int deleteUser(Long id);
// 通過id查詢
User findUserbyId(Long id);
}
3.2 dao層實(shí)現(xiàn)類
dao層的實(shí)現(xiàn)類才是具體操作sql的地方。
/**
* @Author lsc
* @Description <p> user 持久層 </p>
* @Date 2019/11/2 10:22
*/
@Repository
public class UserDaoImpl implements UserDao {
// 注入jdbc模板
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int addUser(User user) {
// sql
String sql = "insert into user (name,telephone) values (?,?)";
// jdbc insert
return jdbcTemplate.update(sql,user.getName(),user.getTelephone());
}
@Override
public int updateUser(User user) {
// sql
String sql = "update user set name = ?, telephone = ? where id = ?";
// jdbc updae
return jdbcTemplate.update(sql,user.getName(),user.getTelephone(),user.getId());
}
@Override
public int deleteUser(Long id) {
// sql
String sql = "delete from user where id = ?";
// delete
return jdbcTemplate.update(sql,id);
}
@Override
public User findUserbyId(Long id) {
// sql
String sql = "select * from user where id = ?";
// params
Object[] params = new Object[]{id};
// rowMapper
BeanPropertyRowMapper rowMapper = new BeanPropertyRowMapper(User.class);
// jdbc query
List<User> query = jdbcTemplate.query(sql, params, rowMapper);
// return user
return query.get(0);
}
}
四 service層
4.1 service層接口
service層接口定義業(yè)務(wù)的方法,提供給控制層調(diào)用。
public interface UserService {
// 添加
int addUser(User user);
// 改
int updateUser(User user);
// 刪
int deleteUser(Long id);
// 通過id查詢
User findUserbyId(Long id);
}
4.2 service層實(shí)現(xiàn)類
service層的實(shí)現(xiàn)類才是具體寫業(yè)務(wù)邏輯代碼的地方。
/**
* @Author lsc
* @Description <p> user service </p>
* @Date 2019/11/2 10:37
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public int addUser(User user) {
return userDao.addUser(user);
}
@Override
public int updateUser(User user) {
return userDao.updateUser(user);
}
@Override
public int deleteUser(Long id) {
return userDao.deleteUser(id);
}
@Override
public User findUserbyId(Long id) {
return userDao.findUserbyId(id) ;
}
}
五 controller
這是一個(gè)簡單的restful層的api,實(shí)現(xiàn)crud功能。
/**
* @Author lsc
* @Description <p>user 控制層 </p>
* @Date 2019/11/2 10:43
*/
@RestController
public class UserController {
@Autowired
UserService userService;
// 查詢user
@GetMapping("user/{id}")
public User getUser(@PathVariable Long id){
return userService.findUserbyId(id);
}
// 添加user
@PostMapping("user")
public int addUser(@RequestBody User user){
return userService.addUser(user);
}
//修改 user
@PutMapping("user/{id}")
public int updateUser(@PathVariable Long id,@RequestBody User user){
user.setId(id);
return userService.updateUser(user);
}
// 刪除user
@DeleteMapping("user/{id}")
public int deleteUser(@PathVariable Long id){
return userService.deleteUser(id);
}
}
六 配置文件
配置文件不使用properties的原因是yml文件的語法格式更加簡練明了,在配置文件中的注解已經(jīng)很詳細(xì),所以不會贅述。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #數(shù)據(jù)庫驅(qū)動(dòng)
url: jdbc:mysql://192.168.0.105:3306/springboot?useUnicode=true&characterEncoding=utf-8 #數(shù)據(jù)庫地址
username: root #數(shù)據(jù)庫賬號
password: 123456 # 數(shù)據(jù)密碼
type: com.alibaba.druid.pool.DruidDataSource # 連接池類型
druid:
#初始化連接池的連接數(shù)量
initial-size: 5
# 最小
min-idle: 5
# 最大
max-active: 20
#配置獲取連接等待超時(shí)的時(shí)間
max-wait: 6000
#配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
time-between-eviction-runs-millis: 6000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
min-evictable-idle-time-millis: 3000
七 pom.xml
很抱歉我把xml放在最后面了
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- jdbc 啟動(dòng)器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql 啟動(dòng)器 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- -->
</dependencies>
八 測試工具說明
大家可以通過postman等開發(fā)工具進(jìn)行restful風(fēng)格接口測試,作為后端開發(fā)者,就別去寫頁面了。
九 測試鏈接池說明
如果大家想知道怎么測試連接池是否連接成功可以實(shí)現(xiàn)ApplicationContextAware接口進(jìn)行測試,具體的代碼如下:
/**
* @Author lsc
* @Description <p> 實(shí)現(xiàn)spring bean 生命周期接口</p>
* @Date 2019/11/2 10:08
*/
@Component
public class DatabaseVision implements ApplicationContextAware {
ApplicationContext applicationContext = null;
// spring ioc 初始化 bean 的時(shí)候調(diào)用
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// 獲得applicationContext
this.applicationContext = applicationContext;
// 獲得dataSource
DataSource dataSource = applicationContext.getBean(DataSource.class);
// 啟動(dòng) springboot application print com.alibaba.druid.pool.DruidDataSource
System.out.println(dataSource.getClass().getName());
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringSession 請求與響應(yīng)重寫的實(shí)現(xiàn)
這篇文章主要介紹了SpringSession 請求與響應(yīng)重寫的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11
Java Mybatis中的 ${ } 和 #{ }的區(qū)別使用詳解
這篇文章主要介紹了Mybatis中的 ${ } 和 #{ }的區(qū)別使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
springmvc直接不經(jīng)過controller訪問WEB-INF中的頁面問題
這篇文章主要介紹了springmvc直接不經(jīng)過controller訪問WEB-INF中的頁面問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
SpringBoot中引入MyBatisPlus的常規(guī)操作
這篇文章主要介紹了SpringBoot中引入MyBatisPlus的常規(guī)操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
詳談spring中bean注入無效和new創(chuàng)建對象的區(qū)別
這篇文章主要介紹了spring中bean注入無效和new創(chuàng)建對象的區(qū)別,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Java Comparator.comparing比較導(dǎo)致空指針異常的解決
這篇文章主要介紹了Java Comparator.comparing比較導(dǎo)致空指針異常的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07

