SpringBoot学习总结(10)之使用JdbcTemplate访问数据库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jokeMqc/article/details/89213835

一、前言

在上篇的博客已经介绍了Sprinboot项目中使用Swagger 构建强大的RESTful API文档,但是我们其中的数据都是写死的,在本篇博客中将介绍使用JdbcTemplate访问数据库。

二、SpringBoot中使用JdbcTemplate

2.1 增加对应的依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-stater-jdbc</artifactId>
		</dependency>
		<!--数据库驱动-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

2.2配置数据源

#数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/joker_mqc
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2.3 创建UserService接口

package com.mqc.service;

import com.mqc.model.User;

import java.util.List;

public interface IUserService {
    /**
     * @description: 获取用户列表
     * @return List<User>
     * @throws
     * @author maoqichuan
     * @date 2019-04-11 16:38
     */
    List<User> getUserList() throws Exception;

    /**
     * @description: 创建用户
     * @return  void
     * @throws
     * @author maoqichuan
     * @date 2019-04-11 16:38
     */
    void postUser(User user) throws Exception;

    /**
     * @description: 获取用户详细信息
     * @return User
     * @throws
     * @author maoqichuan
     * @date 2019-04-11 16:39 
     */
    User getUser(String id) throws Exception;

    /**
     * @description: 根据用户id更新用户信息
     * @return void
     * @throws
     * @author maoqichuan
     * @date 2019-04-11 16:41 
     */
    void putUser(String id,User user) throws Exception;

    /**
     * @description: 删除用户信息
     * @return void
     * @throws Exception
     * @author maoqichuan
     * @date 2019-04-11 16:42 
     */
    void deleteUser(String id) throws Exception;
}

2.4 创建UserServiceIImpl实现类

package com.mqc.service.impl;

import com.mqc.model.User;
import com.mqc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author maoqichuan
 * @ClassName: UserServiceImpl
 * @description: UserServiceImpl
 * @date 2019-04-1116:43
 **/
@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private JdbcTemplate jdbctemplate;

    @Override
    public List<User> getUserList() throws Exception {
        List<User> list = new ArrayList<>();

        jdbctemplate.query("SELECT username,userphone,userage FROM user_info", new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                User user = new User();
                user.setUserName(rs.getString("username"));
                user.setUserPhone(rs.getString("userphone"));
                user.setUserAge(rs.getInt("userage"));

                list.add(user);
            }
        });
        return list;
    }

    @Override
    public void postUser(User user) throws Exception {
        jdbctemplate.update(" INSERT INTO user_info(username,userphone,userage) VALUES (?,?,?)",user.getUserName()
            ,user.getUserPhone(),user.getUserAge());
    }

    @Override
    public User getUser(String id) throws Exception {
        List<User> list = jdbctemplate.query("select username,userphone,userage from user_info where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class));

        if (list != null && list.size() > 0) {
            return list.get(0);
        }else {
            return null;
        }
    }


    @Override
    public void putUser(String id, User user) throws Exception {
        int size = jdbctemplate.update(" UPDATE user_info SET username=?,userphone=?,userAge=? where id=?",
                user.getUserName(), user.getUserPhone(), user.getUserAge(), id);

        if(size <= 0){
            throw new Exception("更新出差");
        }
    }

    @Override
    public void deleteUser(String id) throws Exception {
        jdbctemplate.update("delete from user_info where id = ?", id);
    }
}

2.5 修改controller

package com.mqc.web;

import com.mqc.model.User;
import com.mqc.service.IUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author maoqichuan
 * @ClassName: RestFulController
 * @description: springboot整合swagger2
 * @date 2019-04-1114:46
 **/
@RestController
@RequestMapping("/users")
public class RestFulController {

    @Autowired
    private IUserService userService;
    /**
     * @description: 获取用户列表,注意RequestMapping的value为空,而请求的方法则要求为get
     * @return List<User>
     * @throws
     * @author maoqichuan
     * @date 2019-04-11 15:42
     */
    @ApiOperation(value = "获取用户列表",notes = "获取用户的列表")
    @RequestMapping(value = "",method = RequestMethod.GET)
    public List<User> getUserList() throws Exception {
        return userService.getUserList();
    }

    /**
     * @description: 创建用户
     * @return String
     * @throws
     * @author maoqichuan
     * @date 2019-04-11 15:43
     */
    @ApiOperation(value = "创建用户",notes = "创建用户")
    @ApiImplicitParam(name = "user",value = "用户实体详细信息",required = true,dataType ="User")
    @RequestMapping(value = "",method = RequestMethod.POST)
    public String postUser(@RequestBody User user) throws Exception {
        userService.postUser(user);
        return "success";
    }


    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable String id) throws Exception {
        return userService.getUser(id);
    }

    @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable String id,User user) throws Exception {
        userService.putUser(id,user);
        return "success";
    }

    @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable String id) throws Exception {
       userService.deleteUser(id);
        return "success";
    }

}

2.6 接口测试

2.6.1 获取用户列表

好了,sprinboot中使用jdbctemplate已经整合完毕了,让我们一起学习一起加油,一起进步!

猜你喜欢

转载自blog.csdn.net/jokeMqc/article/details/89213835
今日推荐