0
点赞
收藏
分享

微信扫一扫

Spring Boot实现SDAO服务

北溟有渔夫 2022-02-15 阅读 64

1.数据库表设计

CREATE DATABASE `springbootlearn`;
CREATE TABLE `student` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `name` varchar(50) NOT NULL DEFAULT '' COMMENT '姓名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `springbootlearn`.`students` (`id`, `name`) VALUES ('1', '小明');
INSERT INTO `springbootlearn`.`students` (`id`, `name`) VALUES ('2', '小花');

2.数据配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springbootlearn
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3.实体层

package com.leo.springbootdemo;

/**
 * 学生实体类
 */
public class Student {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

4.Mapper层

package com.leo.springbootdemo;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

/**
 * 学生Mapper
 */
@Mapper
@Repository
public interface StudentMapper {
    @Select("select * from student where id = #{id}")
    Student findById(Integer id);
}

5.service层

package com.leo.springbootdemo;

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

/**
 * 学生Service
 */
@Service
public class StudentService {
    @Autowired
    StudentMapper studentMapper;
    public Student findStudent(Integer id) {
        return studentMapper.findById(id);
    }
}

6.controller层

package com.leo.springbootdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {

    @Autowired
    StudentService studentService;

    @GetMapping({"/student"})
    public String student(@RequestParam Integer id) {
        Student student = studentService.findStudent(id);
        return student.toString();
    }
}

7.执行

举报

相关推荐

0 条评论