直接上干貨:
一、項目搭建以及環境需要:
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