SpringBoot系列(17):基于Spring内置的JdbcTemplate实现极简CRUD功能

摘要:现如今市面上以Java技术栈为主、用于开发Web项目的主流持久层框架主要包括Hibernate、JPA、Spring Data JPA、ibatis、Mybatis等等,其中,用的比较多的当属Mybatis、Hibernate/ Spring Data JPA,即所谓的SSM或者SSH项目啦!本文我们将基于Spring内置的JdbcTemplate实现一个功能模块的CRUD操作。

内容:对于目前市面上流行的持久层框架Mybatis、Hibernate/ Spring Data JPA,相信大家或多或少都见过,甚至有的小伙伴都已经用它们来撸过N套项目了,本文我们就不分享介绍这些主流框架的应用了。相反,我们回归到核心框架Spring中内置JdbcTemplate组件,一起来体验一下Spring 内置的JdbcTemplate如何实现一个业务模块的CRUD操作功能。

JdbcTemplate,顾名思义,其实是从传统的JDBC操作组件演进而来的,但是它却不能等同于传统的JDBC(否则,就没有介绍的必要了),它屏蔽了传统JDBC的数据库连接操作、语句管理以及资源关闭管理等既繁琐、而又重复性的操作代码,采用“模板设计模式”,并基于强大的Spring框架作为依托而隆重推出的操作数据库的利器!

在对业务模块进行CRUD等功能操作之前,我们需要在我们的项目中显示、自动注入JdbcTempalte操作组件(当然啦,你如果喜欢用XML进行配置,那也完全是ok的)!

    @Bean("primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource){
        JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

在这里,我们需要注入主数据源primaryDataSource实例,用来构造JdbcTemplate实例。之后我们以数据库表user为案例,分享介绍极简的CRUD功能,其中,该数据库表user的DDL定义如下所示:  

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '名字',
  `code` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '工号',
  `email` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '邮箱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';

(1)首先,我们自然需要创建一个Controller,用于接收前端过来的请求数据,这个controller下自然由CRUD几个方法,其完整的源代码如下所示:  

/**
 * spring jdbcTemplate
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868 qq-> 1948831260
 * @Date: 2019/11/11 21:33
 **/
@RestController
@RequestMapping("jdbc/template/user")
public class JbdcTemplateController extends AbstractController{

    @Autowired
    private JdbcTemplateService jdbcTemplateService;

    //TODO:新增
    @RequestMapping(value = "add",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse info(@RequestBody @Validated UserDto userDto, BindingResult result){
        String checkRes=ValidatorUtil.checkResult(result);
        if (StringUtils.isNotBlank(checkRes)){
            return new BaseResponse(StatusCode.InvalidParams.getCode(),checkRes);
        }
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            int res=jdbcTemplateService.addUser(userDto);
            response.setData(res);

        }catch (Exception e){
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    //TODO:查询一个
    @RequestMapping(value = "query/one",method = RequestMethod.GET)
    public BaseResponse queryOne(@RequestParam Integer id){
        if (id<=0){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            response.setData(jdbcTemplateService.queryUserById(id));

        }catch (Exception e){
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    //TODO:查询列表
    @RequestMapping(value = "query/list",method = RequestMethod.GET)
    public BaseResponse queryList(@RequestParam String search){
        BaseResponse response=new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap= Maps.newHashMap();
        try {
            resMap.put("数据列表-v1",jdbcTemplateService.queryListV1(search));
            resMap.put("数据列表-v2",jdbcTemplateService.queryListV2(search));

        }catch (Exception e){
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        response.setData(resMap);
        return response;
    }

    //TODO:删除
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public BaseResponse delete(@RequestParam Integer id){
        if (id<=0){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            response.setData(jdbcTemplateService.delete(id));

        }catch (Exception e){
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }
}

更多请见:http://www.mark-to-win.com/tutorial/51027.html 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值