第二篇 : SpringBoot 2.x中使用JdbcTemplate

简介: 数据文件DROP TABLE IF EXISTS users;CREATE TABLE users ( id INT ( 11 ) PRIMARY KEY AUTO_INCREMENT, username VARCHAR ( 255 ) NO...

数据文件

DROP TABLE IF EXISTS users;

CREATE TABLE users ( 
id INT ( 11 ) PRIMARY KEY AUTO_INCREMENT, 
username VARCHAR ( 255 ) NOT NULL, 
passwd VARCHAR ( 255 ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8;

INSERT users VALUES ( NULL, '翠花', '123' );
INSERT users VALUES ( NULL, '王卫国', '123' );
INSERT users VALUES ( NULL, '李小花', '123' );
INSERT users VALUES ( NULL, '王二柱', '123' );
INSERT users VALUES ( NULL, '赵铁蛋', '123' );

需要引入的依赖

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

application.properties

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

application.yml

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

User.java

package com.prvi.gabriel.springbootforjdbctemplate.entity;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-08
 * @Desciption:
 */
public class User {

    private long id;

    private String username;

    private String password;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

UserController.java

package com.prvi.gabriel.springbootforjdbctemplate.controller;

import com.prvi.gabriel.springbootforjdbctemplate.entity.User;
import com.prvi.gabriel.springbootforjdbctemplate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-08
 * @Desciption:
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(name = "/",method = RequestMethod.GET)
    public List<User> usersList(){
        List<User> users = null;
        return userService.findUsers();
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public User getUserById(@PathVariable long id){
        return userService.findUserById(id);
    }

    @RequestMapping(name = "/",method = RequestMethod.POST,produces = "text/plain;charset=utf-8")
    public String addUser(User user){
        System.out.println(user);
        if(userService.saveUser(user) > 0 ){
            return "新增成功";
        }else{
            return "新增失败";
        }
    }

    @RequestMapping(name = "/",method = RequestMethod.PUT)
    public String updateUserById(User user){
        if(userService.updateUser(user) > 0 ){
            return "修改成功";
        }else{
            return "修改失败";
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String deleteUserById(@PathVariable long id){
        if(userService.delUserById(id) > 0 ){
            return "删除成功";
        }else{
            return "删除失败";
        }
    }
}

UserService.java

package com.prvi.gabriel.springbootforjdbctemplate.service;

import com.prvi.gabriel.springbootforjdbctemplate.entity.User;

import java.util.List;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-08
 * @Desciption:
 */
public interface UserService {

    List<User> findUsers();

    User findUserById(long id);

    int saveUser(User user);

    int delUserById(long id);

    int updateUser(User user);

}

UserServiceImpl.java

package com.prvi.gabriel.springbootforjdbctemplate.service;

import com.prvi.gabriel.springbootforjdbctemplate.entity.User;
import com.prvi.gabriel.springbootforjdbctemplate.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-08
 * @Desciption:
 */
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserRepository repository;

    @Transactional(readOnly = true)
    @Override
    public List<User> findUsers() {
        return repository.findUsers();
    }

    @Transactional(readOnly = true)
    @Override
    public User findUserById(long id) {
        return repository.findUserById(id);
    }

    @Transactional
    @Override
    public int saveUser(User user) {
        return repository.saveUser(user);
    }

    @Transactional
    @Override
    public int delUserById(long id) {
        return repository.delUserById(id);
    }

    @Transactional
    @Override
    public int updateUser(User user) {
        return repository.updateUser(user);
    }
}

UserRepository.java

package com.prvi.gabriel.springbootforjdbctemplate.repository;

import com.prvi.gabriel.springbootforjdbctemplate.entity.User;

import java.util.List;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-08
 * @Desciption:
 */
public interface UserRepository {

    List<User> findUsers();

    User findUserById(long id);

    int saveUser(User user);

    int delUserById(long id);

    int updateUser(User user);
}

UserRepositoryImpl.java

package com.prvi.gabriel.springbootforjdbctemplate.repository;

import com.prvi.gabriel.springbootforjdbctemplate.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-08
 * @Desciption:
 */
@Repository
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<User> findUsers() {
        return jdbcTemplate.query("select * from users",new UserMapper());
    }

    @Override
    public User findUserById(long id) {
        List<User> users = jdbcTemplate.query("select * from users where id = ?",new Object[]{id},new UserMapper());
        User user = null;
        if(users != null&&!users.isEmpty()){
            user = users.get(0);
        }
        return user;
    }

    @Override
    public int saveUser(User user) {
        return jdbcTemplate.update("insert into users (username,password) values (?,?)",new Object[]{user.getUsername(),user.getPassword()});
    }

    @Override
    public int delUserById(long id) {
        return jdbcTemplate.update("delete from users where id = ?",new Object[]{id});
    }

    @Override
    public int updateUser(User user) {
        return jdbcTemplate.update("update users set username = ? , password = ? where id = ?",new Object[]{user.getUsername(),user.getPassword(),user.getId()});
    }
}

class UserMapper implements RowMapper<User>{

    @Override
    public User mapRow(ResultSet resultSet, int i) throws SQLException {
        User user = new User();
        user.setId(resultSet.getLong("id"));
        user.setUsername(resultSet.getString("username"));
        user.setPassword(resultSet.getString("password"));
        return user;
    }
}

UserControllerTest.java

package com.prvi.gabriel.springbootforjdbctemplate.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-08
 * @Desciption:
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserControllerTest {

    @Autowired
    private WebApplicationContext context;
    private MockMvc mockMvc;

    @Before
    public void setUp(){
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }
    @Test
    public void usersList() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/users"));
    }

    @Test
    public void getUserById() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/users/1"));
    }

    @Test
    public void addUser() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/users").param("username","脚后跟").param("password","123"));
    }

    @Test
    public void updateUserById() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.put("/users").param("id","1").param("username","李海军").param("password","456"));
    }

    @Test
    public void deleteUserById() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.delete("/users/3"));
    }
}
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
Java 数据库连接 数据库
SpringBoot整合持久层技术之搭建JDBCTemplate项目实战
现在有了MyBatis之后很少人使用JDBCTemplate来整合项目了,要么就是JPA技术,要么就是Mybatis来操作数据库,今天我搭建一个springboot的template项目,看看其和JPA、Mybatis有什么不同的地方,方便大家一起学习。
293 0
|
Java 关系型数据库 MySQL
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
这篇文章是关于如何使用Spring Boot框架通过JdbcTemplate操作MySQL数据库的教程。
1653 0
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
|
Java 关系型数据库 数据库连接
SpringBoot(八)之JdbcTemplate
在 application.properties 或 application.yml 文件中配置数据库连接信息。
1217 0
|
Java 关系型数据库 MySQL
Spring Boot使用JdbcTemplate操作mysql数据库实战(附源码 超详细)
Spring Boot使用JdbcTemplate操作mysql数据库实战(附源码 超详细)
866 0
|
Java 数据库连接 测试技术
微服务技术系列教程(03) - SpringBoot - 整合各种数据源(JdbcTemplate、MyBatis、JPA)
微服务技术系列教程(03) - SpringBoot - 整合各种数据源(JdbcTemplate、MyBatis、JPA)
290 0
|
Oracle NoSQL 关系型数据库
SpringBoot-13-使用JdbcTemplate链接Mysql数据库
在企业项目开发者,数据库的使用是必不可少的一部分,常用的数据库有mysql、oracle、sqlserver、redis等,我们接下来的几章会介绍SpringBoot中如何使用数据库,本章就介绍使用JdbcTemplate链接mysql。
328 0
|
SQL 存储 druid
Spring Boot数据持久化之JdbcTemplate
Spring Boot数据持久化之JdbcTemplate
|
XML Java 关系型数据库
SpringBoot 整合 JdbcTemplate|学习笔记
快速学习 SpringBoot 整合 JdbcTemplate
271 0
SpringBoot 整合 JdbcTemplate|学习笔记
|
SQL Java 关系型数据库
Spring Boot常用数据库开发技术总结:JDBCTemplate、JPA、Mybatis
1.概述 数据库开发一直是JAVA开发的核心之一,作为现在JAVA EE的基石框架,Spring Boot自身携带了一个JDBCTemplate框架,其对JDBC进行了基础的封装,使得Spring Boot原生就支持据库开发。同时Spring Boot也不排斥其它优秀的持久层框架,允许他们以极低的代价平滑的接入。 本文主要介绍最常用到的三个持久层框架,JdbcTemplate、JPA、mybatis如何接入Spring Boot并在其上进行开发。
701 0