构建业务

做好前后端分离,前端用vue框架,有前端人员开发实现 。

后面按照contorller-->ervice-->dao-->mysql的顺序进行调用 。

1.创建表

DROP TABLE IF EXISTS `student`;

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.建entity实体类

在com.hcb.springcloud下新建Entites.Student类。

引入三个注解。

@AllArgsConstructor

​ 自动生成全参的构造函数

@NoArgsConstructor

​ 自动生成无参的构造函数

@Data注解

@Data注解 表示:在Java代码中不需要生成getter and setter,而在编译的时候会自动生成getter and setter。

编译的时候 会做如下操作

  • 所有属性的get和set方法
  • toString 方法
  • hashCode方法
  • equals方法
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id ;
    private String name;    
}

3.封装前端返回实体commonresult

加一个两参的构造函数,在T为null时用。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
    private int code;
    private String msg;
    private T data;
    public CommonResult(int code,String msg){
        this(code,msg,null);
    }
}

4.创建dao接口

dao是和数据库打交道的。 data access object

DAO 模式提供了访问关系型数据库系统所需操作的接口,将数据访问和业务逻辑分离对上层提供面向对象的数据访问接口.就是将数据库操作都封装起来。

引用的mapper推荐使用org.apache.ibatis.annotations.Mapper;

如果用org.springframework.stereotype.Repository,那么插入的时候 会有问题。

import com.hcb.springcloud.Entities.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentDao {
    public int create(Student student);
    public Student getStudentById(@Param("id") int id);
}
Param参数

org.apache.ibatis.annotations.Param 在使用的时候 只要参入参数名就可以了。

select * from user where user_id= #{userId,jdbcType=VARCHAR} and password=#{password,jdbcType=VARCHAR}

org.springframework.data.repository.query.Param ,参数需要按先后顺序传入

select * from user where user_id= #{0,jdbcType=VARCHAR} and password=#{1,jdbcType=VARCHAR}

5.创建Mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hcb.springcloud.dao.StudentDao">
    <insert id="create" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
        insert  into student(name) values(#{student})
    </insert>

    <resultMap id="BaseResultMap" type="com.hcb.springcloud.entities.Student">
        <id column="id" property="id" jdbcType="INTEGER"></id>
        <id column="name" property="name" jdbcType="VARCHAR"></id>
    </resultMap>
    <select id="getStudentById" parameterType="Int" resultMap="BaseResultMap">
        select * from student where id=${id};
    </select>

</mapper>

xml中namespace强制的是映射哪个dao接口。

parameterType="Student": 这个参数类型指定实例,因为在application.yml中配置了

mybatis:
  mapperlocation:classpath:mapper/*.xml
  type-aliases-package:com.hcb.springcloud.entities #entity别名类所在的包。

所以会扫描entities文件夹下的所有类。找到student

useGeneratedKeys="true" :表示插入的表id以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键id返回, 在dao接口中,插入的数据通过返回的类型是int类型

resultMap:表示自己定义的一个返回的map对应关系

resultType:表示返回的是实体类

resultMap中定义的id要复制getStudentById标签中的resultmap中的值,

resultMap中定义的type 要去实体类中复制下引用的路径加类名。

6创建service

创建Service.StudentSerivce的接口,把dao的接口中对应的代码复制过来

在创建impl.StudentSerivce 实现来,来继承StudentSerivce

public interface StudentService {
    public int create(Student student);
    public Student getStudentById(@Param("id") int id);
}

public class StudentService implements com.hcb.springcloud.Service.StudentService {
    @Resource
    private StudentDao dao;
    public int create(Student student) {
        return dao.create(student);
    }

    public Student getStudentById(int id) {
        return dao.getStudentById(id);
    }
}

@Resource注解为类配置注入对象

java为我们提供了 javax.annotation.Resource这个注解。

spring框架提供了org.springframework.beans.factory.annotation.Autowired。

一般情况下我们使用 javax.annotation.Resource这个注解,因为这样我们就能实现和spring框架的解藕

两者的区别参考:https://blog.csdn.net/weixin_40423597/article/details/80643990

@Autowired按byType自动注入,

@Resource默认按 byName自动注入罢了

7.创建Controller

@RestController = @Controller + @ResponseBody

@Controller 将当前修饰的类注入SpringBoot IOC容器,使得从该类所在的项目跑起来的过程中,这个类就被实例化

@ResponseBody 以Json字符串的形式返回给客户端,如果返回的是String类型,则仍然是String

@Slf4j 为类提供一个 属性名为log 的 log4j 日志对像

如果要把日志输出到文件,要在yml或者properties配置文件中进行配置

//yml
logging:
    file:d:\\log\\test.log

//propropies
logging.file=D:\\log\\test.log

@RestController
@Slf4j
public class StudentController {
    @Resource
    private StudentService studentService;

    @PostMapping(value = "/student/create")
    public CommonResult create(Student student){
        int result=studentService.create(student);
        log.info("insert success");
        if(result>0){
            return new CommonResult(200,"success",result);
        }
        else {
            return new CommonResult(404,"error");
        }
    }

    @GetMapping(value = "/student/get/{id}")
    public CommonResult getStudentById(@PathVariable("id") Integer id){
        Student result=studentService.getStudentById(id);
        log.info(" success");
        if(result!=null){
            return new CommonResult(200,"success",result);
        }
        else {
            return new CommonResult(404,"error");
        }
    }
}

8.测试结果

浏览器输入http://localhost:8001/student/get/1 获得结果

image-20210324221725384


本文由 hcb 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论