SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates訪問Mysql

本文介紹springboot經過jdbc訪問關係型mysql,經過spring的JdbcTemplate去訪問。前端

準備工做

jdk 1.8
maven 3.0
idea
mysql

初始化mysql

-- create table `account`
DROP TABLE `account` IF EXISTS
CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `money` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');

建立工程

引入依賴:java

在pom文件引入spring-boot-starter-jdbc的依賴:mysql

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

引入mysql鏈接類和鏈接池:git

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.29</version>
</dependency>

開啓web:程序員

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

配置相關文件

在application.properties文件配置mysql的驅動類,數據庫地址,數據庫帳號、密碼信息。github

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456

經過引入這些依賴和配置一些基本信息,springboot就能夠訪問數據庫類。 具體編碼web

實體類

public class Account {
    private int id ;
    private String name ;
    private double money;

....省略了getter. setter

}

dao層

public interface IAccountDAO {
    int add(Account account);

    int update(Account account);

    int delete(int id);

    Account findAccountById(int id);

    List<Account> findAccountList();
}

dao具體的實現類

package com.forezp.dao.impl;

import com.forezp.dao.IAccountDAO;
import com.forezp.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by fangzhipeng on 2017/4/20.
 */
[@Repository](https://my.oschina.net/u/3055569)
public class AccountDaoImpl implements IAccountDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    [@Override](https://my.oschina.net/u/1162528)
    public int add(Account account) {
        return jdbcTemplate.update("insert into account(name, money) values(?, ?)",
              account.getName(),account.getMoney());

    }

    [@Override](https://my.oschina.net/u/1162528)
    public int update(Account account) {
        return jdbcTemplate.update("UPDATE  account SET NAME=? ,money=? WHERE id=?",
                account.getName(),account.getMoney(),account.getId());
    }

    [@Override](https://my.oschina.net/u/1162528)
    public int delete(int id) {
        return jdbcTemplate.update("DELETE from TABLE account where id=?",id);
    }

    @Override
    public Account findAccountById(int id) {
        List<Account> list = jdbcTemplate.query("select * from account where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Account.class));
        if(list!=null && list.size()>0){
            Account account = list.get(0);
            return account;
        }else{
            return null;
        }
    }

    @Override
    public List<Account> findAccountList() {
        List<Account> list = jdbcTemplate.query("select * from account", new Object[]{}, new BeanPropertyRowMapper(Account.class));
        if(list!=null && list.size()>0){
            return list;
        }else{
            return null;
        }
    }
}

service層

public interface IAccountService {


    int add(Account account);

    int update(Account account);

    int delete(int id);

    Account findAccountById(int id);

    List<Account> findAccountList();

}

service具體實現類

@Service
public class AccountService implements IAccountService {
    @Autowired
    IAccountDAO accountDAO;
    @Override
    public int add(Account account) {
        return accountDAO.add(account);
    }

    @Override
    public int update(Account account) {
        return accountDAO.update(account);
    }

    @Override
    public int delete(int id) {
        return accountDAO.delete(id);
    }

    @Override
    public Account findAccountById(int id) {
        return accountDAO.findAccountById(id);
    }

    @Override
    public List<Account> findAccountList() {
        return accountDAO.findAccountList();
    }
}

構建一組restful api來展現

package com.forezp.web;

import com.forezp.entity.Account;
import com.forezp.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by fangzhipeng on 2017/4/20.
 */

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    IAccountService accountService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public  List<Account> getAccounts(){
       return accountService.findAccountList();
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public  Account getAccountById(@PathVariable("id") int id){
        return accountService.findAccountById(id);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public  String updateAccount(@PathVariable("id")int id , @RequestParam(value = "name",required = true)String name,
    @RequestParam(value = "money" ,required = true)double money){
        Account account=new Account();
        account.setMoney(money);
        account.setName(name);
        account.setId(id);
        int t=accountService.update(account);
        if(t==1){
            return account.toString();
        }else {
            return "fail";
        }
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    public  String postAccount( @RequestParam(value = "name")String name,
                                 @RequestParam(value = "money" )double money){
        Account account=new Account();
        account.setMoney(money);
        account.setName(name);
        int t= accountService.add(account);
        if(t==1){
            return account.toString();
        }else {
            return "fail";
        }

    }

}

能夠經過postman來測試,具體的我已經所有測試經過,沒有任何問題。注意restful構建api的風格。面試

源碼下載:https://github.com/forezp/SpringBootLearningspring

參考資料

relational-data-accesssql

寫在最後

歡迎關注喜歡、和點贊後續將推出更多的spring cloud教程,敬請期待。 歡迎關注個人微信公衆號獲取更多更全的學習資源,視頻資料,技術乾貨! 歡迎掃碼關注

公衆號回覆「學習」,拉你進程序員技術討論羣乾貨資源第一時間分享。

公衆號回覆「視頻」,領取800GJava視頻學習資源。 java學習全套 820G資源

公衆號回覆「全棧」,領取1T前端Java產品經理微信小程序Python等資源合集大放送。 全棧資料 接近1T資源

公衆號回覆「慕課」,領取1T慕課實戰學習資源。 慕課實戰大全 1061G資源

公衆號回覆「實戰」,領取750G項目實戰學習資源。 先後端實戰項目 750實戰資源

公衆號回覆「面試」,領取8G面試實戰學習資源。 JAVA面試實戰視頻 8G面試資源

https://blog.csdn.net/forezp/article/details/70341818 本文出自方誌朋的博客

相關文章
相關標籤/搜索