溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Springboot集成jdbcTemplate的用法

發(fā)布時間:2020-08-01 11:05:46 來源:億速云 閱讀:168 作者:小豬 欄目:編程語言

這篇文章主要講解了Springboot集成jdbcTemplate的用法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

一 說明

實際工作中其實很少會用到jdbcTemplate去操作數(shù)據(jù)庫,因為其使用方式不是很靈活,sql的拼接能力不強;實際上jdbcTemplate是屬于spring自帶的數(shù)據(jù)層模板,在spring中可以說是比較失敗的一個案例,原因是當代流行mybatis當做持久層訪問數(shù)據(jù)庫,其優(yōu)越的sql拼接能力、動態(tài)sql、半自動化映射、和易于sql優(yōu)化的特性,深受廣大互聯(lián)網(wǎng)公司的喜愛,并且mybatis的市場占有率不斷的上升,hibernate的市場不斷縮水,可以說hibernate已經(jīng)這種強映射關系的持久層模型已經(jīng)走到互聯(lián)網(wǎng)時代的盡頭了。

本文寫jdbcTemplate只是當作大家的一個入門學習,可以說以后你很難用到這門技術,所以不會深入研究,有興趣的朋友可以專欄我其他關于springboot的集成系列。本次演示使用jdk1.8,mysql5.6,springboot2.1。​

二數(shù)據(jù)庫建表和實體

user表,里面有三個屬性 用戶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表對應的實體:

/**
 * @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操作方法,其實現(xiàn)類則進行具體的sql操作,很多開發(fā)人員沒有這種解耦的思想,往往就直接在servic層操作sql,可以說沒有完整的一個知識體系,往往會造成后期維護困難,項目無法進行下去;

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層實現(xiàn)類

dao層的實現(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 (&#63;,&#63;)";
    // jdbc insert
    return jdbcTemplate.update(sql,user.getName(),user.getTelephone());
  }

  @Override
  public int updateUser(User user) {
    // sql
    String sql = "update user set name = &#63;, telephone = &#63; where id = &#63;";
    // 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 = &#63;";
    // delete
    return jdbcTemplate.update(sql,id);
  }

  @Override
  public User findUserbyId(Long id) {
    // sql
    String sql = "select * from user where id = &#63;";
    // 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è)務的方法,提供給控制層調(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層實現(xiàn)類

service層的實現(xiàn)類才是具體寫業(yè)務邏輯代碼的地方。

/**
 * @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

這是一個簡單的restful層的api,實現(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)很詳細,所以不會贅述。

spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #數(shù)據(jù)庫驅(qū)動
url: jdbc:mysql://192.168.0.105:3306/springboot&#63;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
#配置獲取連接等待超時的時間
max-wait: 6000
#配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
time-between-eviction-runs-millis: 6000
# 配置一個連接在池中最小生存的時間,單位是毫秒
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 啟動器-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- mysql 啟動器 -->
    <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ā)工具進行restful風格接口測試,作為后端開發(fā)者,就別去寫頁面了。

九 測試鏈接池說明

如果大家想知道怎么測試連接池是否連接成功可以實現(xiàn)ApplicationContextAware接口進行測試,具體的代碼如下:

/**
 * @Author lsc
 * @Description <p> 實現(xiàn)spring bean 生命周期接口</p>
 * @Date 2019/11/2 10:08
 */
@Component
public class DatabaseVision implements ApplicationContextAware {

  ApplicationContext applicationContext = null;
  // spring ioc 初始化 bean 的時候調(diào)用
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    // 獲得applicationContext
    this.applicationContext = applicationContext;
    // 獲得dataSource
    DataSource dataSource = applicationContext.getBean(DataSource.class);
    // 啟動 springboot application print com.alibaba.druid.pool.DruidDataSource
    System.out.println(dataSource.getClass().getName());
  }
}

看完上述內(nèi)容,是不是對Springboot集成jdbcTemplate的用法有進一步的了解,如果還想學習更多內(nèi)容,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI