资讯专栏INFORMATION COLUMN

SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问My

tigerZH / 368人阅读

摘要:本文介绍通过访问关系型通过的去访问。通过引入这些依赖和配置一些基本信息,就可以访问数据库类。具体编码实体类省略了层具体的实现类层具体实现类构建一组来展示可以通过来测试,具体的我已经全部测试通过,没有任何问题。注意构建的风格。

本文介绍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");
创建工程

引入依赖:

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

 
    org.springframework.boot
    spring-boot-starter-jdbc

引入mysql连接类和连接池:


    mysql
    mysql-connector-java
    runtime



    com.alibaba
    druid
    1.0.29

开启web:

    
        org.springframework.boot
        spring-boot-starter-web
    
配置相关文件

在application.properties文件配置mysql的驱动类,数据库地址,数据库账号、密码信息。

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就可以访问数据库类。
具体编码

实体类
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 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
public class AccountDaoImpl implements IAccountDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int add(Account account) {
        return jdbcTemplate.update("insert into account(name, money) values(?, ?)",
              account.getName(),account.getMoney());

    }

    @Override
    public int update(Account account) {
        return jdbcTemplate.update("UPDATE  account SET NAME=? ,money=? WHERE id=?",
                account.getName(),account.getMoney(),account.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("DELETE from TABLE account where id=?",id);
    }

    @Override
    public Account findAccountById(int id) {
        List 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 findAccountList() {
        List 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 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 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 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/Spr...

参考资料

relational-data-access

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70356.html

相关文章

  • SpringBoot-JdbcTemplates-MySQL

    摘要:中用访问一准备工作运行二启动容器并进行表的创建启动查看镜像启动查看全部的镜像对应的启动连接创建数据库创建表三使用创建项目选择四配置相关的文件配置配置实体类类名为层接口实现类层接口实现类层控制层五使用进行测试没有安装的话可以 SpringBoot 中用 JdbcTemplate 访问MySQL 一. 准备工作 IDEA docker : 运行MySql 二. 启动 docker my...

    CoffeX 评论0 收藏0
  • SpringBoot官方教程 | 第十三篇springboot集成spring cache

    摘要:本文介绍如何在中使用默认的声明式缓存定义和接口用来统一不同的缓存技术。在使用集成的时候,我们需要注册实现的的。默认使用在我们不使用其他第三方缓存依赖的时候,自动采用作为缓存管理器。源码下载参考资料揭秘与实战二数据缓存篇快速入门 本文介绍如何在springboot中使用默认的spring cache 声明式缓存 Spring 定义 CacheManager 和 Cache 接口用来统一不...

    Magicer 评论0 收藏0
  • SpringBoot 实战 (六) | JdbcTemplates 访问 Mysql

    摘要:微信公众号一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。前言如题,今天介绍通过访问关系型通过的去访问。我这里已经全部测试通过,请放心使用。源码下载后语以上用访问的教程。另外,关注之后在发送可领取免费学习资料。 微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。 前言 如题,今天介绍 springboot 通过jdbc访问关系型mysql,通过...

    wh469012917 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<