SpringBoot-JdbcTemplate-Demo练手小案例(Eclipse)

Posted superdrew

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot-JdbcTemplate-Demo练手小案例(Eclipse)相关的知识,希望对你有一定的参考价值。

直接上干货:

一、项目搭建以及环境需要

1. JDK版本:1.8

2. Maven版本:3.X

3. SpringBoot版本:2.1.3.RELEASE

4. Eclipse neon3(编辑器)

5. Navcat(数据库GUI)

二、项目框架

技术图片

三、数据库文件:

1. 数据库为:mydb, 数据表为:student

CREATE TABLE `student` (
  `stu_id` int(2) NOT NULL,
  `stu_name` varchar(32) NOT NULL,
  `stu_age` int(3) NOT NULL,
  `stu_sex` set(‘男‘,‘女‘) DEFAULT ‘‘,
  PRIMARY KEY (`stu_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘学生表‘;

2. Navcat管理数据界面:

技术图片

3. 搭建好项目demo框架:

① 新建entity包。dao包、service包、controller包。(注意:springBootDemoApplication.java与这些包同级别)

② 导入springboot所需要的依赖包:

maven中pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.drew</groupId>
	<artifactId>spring-test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-test</name>
	<description>Drew-test-Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

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

		<!--引入web依赖,可以使用@RequestMapping,@RestController等注解 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!--引入mysql连接 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!--引入JDBC的依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!-- 设置spring boot为热部署 :spring-boot-devtools(Springboot 版本为1.3.0以上,推荐) 
			还有其他的方法进行热不是本来有三种方式的。 -->
		<!-- 学习连接:https://www.cnblogs.com/xiangchun/p/8442487.html -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
		</dependency>

		<dependency>
			<groupId>net.bytebuddy</groupId>
			<artifactId>byte-buddy</artifactId>
		</dependency>
		<dependency>
			<groupId>net.bytebuddy</groupId>
			<artifactId>byte-buddy-agent</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>


	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

  ② 将application.properties后缀改成 .yml

application.yml文件内容:

server:
    port: 8888

spring:
    datasource:
        url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true&serverTimezone=GMT%2B8
        username: root
        password: root
        driver-class-name: com.mysql.cj.jdbc.Driver

4. 补充内容:

① entity / Student.java

package com.drew.entity;

/**
 * @author zero 2019/03/23
 */
public class Student {
    
    private Integer stuId;
    private String stuName;
    private Integer stuAge;
    private String stuSex;
    public Integer getStuId() {
        return stuId;
    }
    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public Integer getStuAge() {
        return stuAge;
    }
    public void setStuAge(Integer stuAge) {
        this.stuAge = stuAge;
    }
    public String getStuSex() {
        return stuSex;
    }
    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }
    
    public Student() {
        super();
    }
    /**
     * @param stuId
     * @param stuName
     * @param stuAge
     * @param stuSex
     */
    public Student(Integer stuId, String stuName, Integer stuAge, String stuSex) {
        super();
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuAge = stuAge;
        this.stuSex = stuSex;
    }
    @Override
    public String toString() {
        return "Student [stuId=" + stuId + ", stuName=" + stuName + ", stuAge=" + stuAge + ", stuSex=" + stuSex + "]";
    }

}

  ② service / StudentService.java (interface)

package com.drew.service;

import java.util.List;

import com.drew.entity.Student;

/**
 * @author zero 2019/03/23
 */
public interface StudentService {
    List<Student> studentList();

    Student findById(Integer stuId);

    Student findByName(String stuName);

    Boolean saveStudent(Student student);

    Boolean updateStudent(Student student);

    Boolean delStudentById(String stuId);
}

  ③ service /  impl / StudentServiceImpl.java

package com.drew.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.drew.dao.StudentDao;
import com.drew.entity.Student;
import com.drew.service.StudentService;

/**
 * @author zero 2019/03/23
 */
@Service
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentDao studentDao;

    @Override
    public List<Student> studentList() {
        return studentDao.studentList();
    }

    @Override
    public Student findById(Integer stuId) {
        return studentDao.findById(stuId);
    }

    @Override
    public Student findByName(String stuName) {
        return studentDao.findByName(stuName);
    }

    @Override
    public Boolean saveStudent(Student student) {
        return studentDao.saveStudent(student);
    }

    @Override
    public Boolean updateStudent(Student student) {
        return studentDao.updateStudent(student);
    }

    @Override
    public Boolean delStudentById(String stuId) {
        return studentDao.delStudentById(stuId);
    }

}

  ③ dao / StudentDao.java

package com.drew.dao;

import java.util.List;

import com.drew.entity.Student;

/**
 * @author zero 2019/03/23
 */
public interface StudentDao {
    
    List<Student> studentList();
    
    Student findById(Integer stuId);
    
    Student findByName(String stuName);
    
    Boolean saveStudent(Student student);
    
    Boolean updateStudent(Student student);
    
    Boolean delStudentById(String stuId);

}

  ④ dao / StudentDaoImpl.java

package com.drew.dao;

import java.util.List;

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 com.drew.entity.Student;

/**
 * @author zero 2019/03/23
 */
@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Student> studentList() {
        String sql = "select * from student";
        List<Student> students = jdbcTemplate.query(sql, new Object[] {}, new BeanPropertyRowMapper(Student.class));
        return students;
    }

    @Override
    public Student findById(Integer stuId) {
        String sql = "select * from student where stu_id = ?";
        List<Student> list = jdbcTemplate.query(sql, new Object[] {stuId}, new BeanPropertyRowMapper(Student.class));
        if (list != null && list.size() > 0) {
            Student student = list.get(0);
            return student;
        } else {
            return null;
        }
    }

    @Override
    public Student findByName(String stuName) {
        String sql = "select * from student where stu_name = ?";
        List<Student> list = jdbcTemplate.query(sql, new Object[] {stuName}, new BeanPropertyRowMapper(Student.class));
        if (list != null && list.size() > 0) {
            Student student = list.get(0);
            return student;
        } else {
            return null;
        }
    }

    @Override
    public Boolean saveStudent(Student student) {
        String sql = "insert into student(stu_id,stu_name,stu_age,stu_sex) values(?,?,?,?)";
        jdbcTemplate.update(sql, student.getStuId(), student.getStuName(), student.getStuAge(), student.getStuSex());
        return true;
    }

    @Override
    public Boolean updateStudent(Student student) {
        String sql = "update student set stu_name = ?,stu_age = ?, stu_sex = ? where stu_id = ?";
        jdbcTemplate.update(sql, student.getStuName(), student.getStuAge(), student.getStuSex(), student.getStuId());
        return true;
    }

    @Override
    public Boolean delStudentById(String stuId) {
        String sql = "delete from student where stu_id = ?";
        jdbcTemplate.update(sql, stuId);
        return true;
    }

}

  ⑤ controller / StudentController.java

package com.drew.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.drew.entity.Student;
import com.drew.service.StudentService;

/**
 * @author zero 2019/03/23
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/listStudent", method = RequestMethod.GET)
    public List<Student> list() {
        return studentService.studentList();
    }

    @RequestMapping(value = "/stuName/{stuName}", method = RequestMethod.GET)
    public Student findStudentByName(@PathVariable("stuName") String stuName) {
        return studentService.findByName(stuName);
    }

    @RequestMapping(value = "/stuId/{stuId}", method = RequestMethod.GET)
    public Student findStudentById(@PathVariable("stuId") Integer stuId) {
        return studentService.findById(stuId);
    }

    @RequestMapping(value = "update", method = RequestMethod.PUT)
    public Map<String, Boolean> update(Student student) {
        Map<String, Boolean> map = new HashMap<>();
        try {
            studentService.updateStudent(student);
            map.put("status", true);
        } catch (Exception e) {
            e.getMessage();
            map.put("status", false);
        }
        return map;
    }

    @RequestMapping(value = "delete", method = RequestMethod.DELETE)
    public Map<String, Boolean> delete(@RequestParam(value = "stuId", required = true) String stuId) {
        Map<String, Boolean> map = new HashMap<>();
        try {
            studentService.delStudentById(stuId);
            map.put("status", true);
        } catch (Exception e) {
            e.getMessage();
            map.put("status", false);
        }
        return map;
    }
}

  ⑥ SpringBootDemoApplication.java(对比下内容)

package com.drew;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * spring boot入口
 * 测试:
 *  http://localhost:8888/student/listStudent
 *  http://localhost:8888/student/stuId/2
 *  http://localhost:8888/student/stuName/Drew
 * @author zero 2019/03/23
 */

@SpringBootApplication
public class SpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootDemoApplication.class, args);
	}

}

四、测试Controller和StudentService

1. 测试controllerTest / MockMVC_HelloControllerTest.java 方法:(MOCK测试)

package com.drew.controllerTest;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.drew.controller.HelloController;
/**
 * 下面是mock测试中必须要的内容;在eclipse中需要手动导入
 */
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author zero 2019/03/23
 * 
 * spring boot测试controller层Demo 
 */
@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class MockMVC_HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testMockMVCTestDemo() throws Exception {
        this.mockMvc.perform(get("/SuperDrew")).andDo(print()).andExpect(status().isOk())
            .andExpect(content().string(containsString("Hello")));
    }

}

2. 测试serviceTest / StudentService.java

package com.drew.serviceTest;


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.SpringRunner;

import com.drew.entity.Student;
import com.drew.service.StudentService;

/*
 * @author zero 2019/03/24
 * 
 * 重点demo内容;
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentServiceTest {
    @Autowired
    private StudentService studentService;
    
    @Test
    public void testStudentService() throws Exception {
        Integer stuId = 1;
        Student student = studentService.findById(stuId);
        System.out.println(student);
    }
}

  3. 至于springtest / SpringTestApplicationTests.java  无关紧要!(省略~)

五、测试结果:

① http://localhost:8888/stuName/Allen

技术图片

② http://localhost:8888/student/stuId/4

技术图片

③ http://localhost:8888/student/listStudent

技术图片

 

以上是关于SpringBoot-JdbcTemplate-Demo练手小案例(Eclipse)的主要内容,如果未能解决你的问题,请参考以下文章