挺久没有时间整理下最近学的东西了,现在整理下吧,哈哈。下面我来写出代码
1.在数据库上新建一张student_info表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for student_info
-- ----------------------------
DROP TABLE IF EXISTS `student_info`;
CREATE TABLE `student_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`sex` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`major` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`height` varchar(100) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=564458 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
并且插入两条数据吧
INSERT INTO `student_info` VALUES (11, '达达', '男', '软件工程', '178');
INSERT INTO `student_info` VALUES (18, '增删改查', '男', '网络工程', '188');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
2.运行成功后,student_info表就创建好了
3.接下来我们在搭建好的SpringBoot中,各自层下写代码,首先写Entity层吧
package com.yoona.entity;
import lombok.Data;
/**
* 学生Entity层
* @author YoonaDa
* @version 2018-10-17
* eg.使用lombok省略get,set等方法
*/
@Data
public class Student {
private int id;
private String name;
private String sex;
private String major;
private String height;
}
这里,我应用了lombok,@Data用于省略下get、set等方法,大家可以通过在pom.xml中添加以下代码
org.projectlombok
lombok
1.16.10
4.StudentMapper.xml的代码
delete from student_info where id=#{id}
insert into
student_info(id,name,sex,major,height)
values
(#{id},#{name},#{sex},#{major},#{height})
update student_info a set
a.name=#{name},
a.sex=#{sex},
a.major=#{major},
a.height=#{height}
where a.id=#{id}
5.dao层的代码如下
package com.yoona.dao;
import com.yoona.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 学生Dao层
* @author YoonaDa
* @version 2018-10-17
*/
@Mapper
public interface StudentDao {
List findStudentById(int id);
int delete(Student id);
List findList(Student student);
void insertList(Student student);
void updateList(Student student);
}
6.Service层的代码如下
package com.yoona.service;
import com.yoona.dao.StudentDao;
import com.yoona.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 学生service层
* @author YoonaDa
* @version 2018-10-17
*/
@Service
public class StudentService {
@Autowired
private StudentDao studentDao;
public List findStudentById(int id){
return studentDao.findStudentById(id);
}
//查出所有数据,并以List的形式返回json
public List findList(Student student){
return studentDao.findList(student);
}
// 根据id删除一整条学生信息
@Transactional(readOnly = false)
public void delete(Student student){
studentDao.delete(student);
}
@Transactional(readOnly = false)
public void insertList(Student student){
studentDao.insertList(student);
}
@Transactional(readOnly = false)
public void updateList(Student student){
studentDao.updateList(student);
}
}
7.controller层代码
package com.yoona.controller;
import com.yoona.common.BaseController;
import com.yoona.common.VResponse;
import com.yoona.entity.Student;
import com.yoona.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 学生Controller
* @author YoonaDa
* @version 2018-10-17
*/
@RestController
@RequestMapping(value = "/stu")
public class StudentController extends BaseController {
@Autowired
private StudentService studentService;
/**
* 用过ID查询信息
* @param id
* @return
*
* eg.http://localhost:8088/stu/findStudentById?id=5
*/
@GetMapping("/findStudentById")
public List findStudentById(int id){
return studentService.findStudentById(id);
}
/**
* 以一个List包含起来,返回的json包含在result中,显示为列表
* @param student
* @return
*
* http://127.0.0.1:8088/stu//findList
*
*/
@GetMapping(value = "/findList")
public VResponse> getList(Student student){
List list =studentService.findList(student);
return VResponse.success(list);
}
/**
* 根据id删除一条数据
* @param student
* @return
*/
@PostMapping(value = "/delete")
public VResponse
这里我要说明一下,此处我用到我封装在common这个包下的VResponse和beanValidator,并且我这里继承于我封装好的一个BaseController,我写出这里的代码吧,可能没这部分复制进去的小伙伴们controller层会有报错
VResponse
package com.yoona.common;
public class VResponse {
private int code = 1;
private String msg = "";
private T result;
//通用错误码
public static final int SUCCESS = 1;
public VResponse(int errCode, String errMsg) {
this.code = errCode;
this.msg = errMsg;
}
public VResponse() {
}
public static VResponse success(T result){
VResponse response = new VResponse(SUCCESS, null);
response.result = result;
return response;
}
public static VResponse success(String msg){
return new VResponse(SUCCESS, msg);
}
public static VResponse success(){
return new VResponse(SUCCESS, null);
}
public static VResponse error(int code,String msg){
VResponse response = new VResponse();
response.setCode(code);
response.setMsg(msg);
return response;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
}
BaseController
package com.yoona.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.List;
public abstract class BaseController {
@Autowired
protected Validator validator;
/**
* 服务端参数有效性验证
* @param object 验证的实体对象
* @param groups 验证组
* @return 验证成功:返回true;严重失败:将错误信息添加到 message 中
*/
protected boolean beanValidator(Model model, Object object, Class>... groups) {
try{
BeanValidators.validateWithException(validator, object, groups);
}catch(ConstraintViolationException ex){
List list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
list.add(0, "数据验证失败:");
addMessage(model, list.toArray(new String[]{}));
return false;
}
return true;
}
/**
* 添加Model消息
* @param
*/
protected void addMessage(Model model, String... messages) {
StringBuilder sb = new StringBuilder();
for (String message : messages){
sb.append(message).append(messages.length>1?"
":"");
}
model.addAttribute("message", sb.toString());
}
}
BeanValidators
package com.yoona.common;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* JSR303 Validator(Hibernate Validator)工具类.
*
* ConstraintViolation中包含propertyPath, message 和invalidValue等信息.
* 提供了各种convert方法,适合不同的i18n需求:
* 1. List, String内容为message
* 2. List, String内容为propertyPath + separator + message
* 3. Map
*
* 详情见wiki: https://github.com/springside/springside4/wiki/HibernateValidator
* @author calvin
* @version 2013-01-15
*/
public class BeanValidators {
/**
* 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void validateWithException(Validator validator, Object object, Class>... groups)
throws ConstraintViolationException {
Set constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set中为List.
*/
public static List extractMessage(ConstraintViolationException e) {
return extractMessage(e.getConstraintViolations());
}
/**
* 辅助方法, 转换Set为List
*/
@SuppressWarnings("rawtypes")
public static List extractMessage(Set extends ConstraintViolation> constraintViolations) {
List errorMessages = Lists.newArrayList();
for (ConstraintViolation violation : constraintViolations) {
errorMessages.add(violation.getMessage());
}
return errorMessages;
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set为Map.
*/
public static Map extractPropertyAndMessage(ConstraintViolationException e) {
return extractPropertyAndMessage(e.getConstraintViolations());
}
/**
* 辅助方法, 转换Set为Map.
*/
@SuppressWarnings("rawtypes")
public static Map extractPropertyAndMessage(Set extends ConstraintViolation> constraintViolations) {
Map errorMessages = Maps.newHashMap();
for (ConstraintViolation violation : constraintViolations) {
errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errorMessages;
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set为List.
*/
public static List extractPropertyAndMessageAsList(ConstraintViolationException e) {
return extractPropertyAndMessageAsList(e.getConstraintViolations(), " ");
}
/**
* 辅助方法, 转换Set为List.
*/
@SuppressWarnings("rawtypes")
public static List extractPropertyAndMessageAsList(Set extends ConstraintViolation> constraintViolations) {
return extractPropertyAndMessageAsList(constraintViolations, " ");
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set为List.
*/
public static List extractPropertyAndMessageAsList(ConstraintViolationException e, String separator) {
return extractPropertyAndMessageAsList(e.getConstraintViolations(), separator);
}
/**
* 辅助方法, 转换Set为List.
*/
@SuppressWarnings("rawtypes")
public static List extractPropertyAndMessageAsList(Set extends ConstraintViolation> constraintViolations,
String separator) {
List errorMessages = Lists.newArrayList();
for (ConstraintViolation violation : constraintViolations) {
errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage());
}
return errorMessages;
}
}
这里还要导入几个jar包,在pom.xml中添加如下代码:
com.google.code.google-collections
google-collect
snapshot-20080530
好了,你会发现现在的代码不会有错误了,哈哈哈,对了,附上一张截图吧。
8.主程序代码
package com.yoona;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@ComponentScan(basePackages="com.yoona.*")
@SpringBootApplication
@MapperScan("com.yoona.dao")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
// 解决跨域问题
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
9.application.yml
server:
port: 8088
spring:
#数据源配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test_springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root123456
mybatis:
#实体类所在包
type-aliases-package: com.yoona.entity
#mapper.xml所在位置
mapper-locations: classpath:mappings/*.xml
10.运行代码了,哈哈哈
11.是时候测试接口了,我们用postman来测试吧
查询所有数据的接口:http://localhost:8088/stu/findList
增加一条数据的接口:http://localhost:8088/stu/insertList
再一次查询时,我们发现是真的成功插进数据库的表中了
测试修改接口吧
http://localhost:8088/stu/updateList
再一次查询出来吧,看看更新成功了没
更改成功了
测试删除接口:
http://localhost:8088/stu/delete
再一次查询,发现真的删除成功了
对了,我差点忘记还有一个通过id查询该id信息的接口
http://localhost:8088/stu/findStudentById?id=11