Spring Boot学习(MVC-MyBatis)

来源:互联网 发布:大学生信用卡额度 知乎 编辑:程序博客网 时间:2024/06/05 23:43

1. 简介MVC

  MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式:

  • Model(模型)表示应用程序核心(比如数据库记录列表)。
  • View(视图)显示数据(数据库记录)。
  • Controller(控制器)处理输入(写入数据库记录)。

  MVC 分层有助于管理复杂的应用程序,因为您可以在一个时间内专门关注一个方面。例如,您可以在不依赖业务逻辑的情况下专注于视图设计。同时也让应用程序的测试更加容易。
  MVC 分层同时也简化了分组开发。不同的开发人员可同时开发视图、控制器逻辑和业务逻辑。

2.Spring Boot+Mybatis

  之前有介绍过简单Hello World的Spring Boot的项目,这里就删了里面的HellWorldController来做这次项目的基础项目(不删也行,不影响),不再从头介绍了。

2.1 建库建表

  建个数据库school,新建个student表吧(还是很怀念学生时光啊~~)
这里写图片描述

2.2 引入Mybatis依赖和配置Mybatis

pom.xml增加

        <dependency>            <groupId>org.mybatis.spring.boot</groupId>            <artifactId>mybatis-spring-boot-starter</artifactId>            <version>1.3.0</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>
# 数据源配置spring.datasource.url=jdbc:mysql://localhost:3306/school?characterEncoding=utf8&useSSL=truespring.datasource.username=rootspring.datasource.password=spring.datasource.driver-class-name=com.mysql.jdbc.Driver# Mybatis配置## 实体类包(扫描后用于别名)mybatis.typeAliasesPackage=cn.yuan.entity## Mapper所在位置mybatis.mapperLocations=classpath:mapper/*.xml# 设置日子级别,用于打印SQLlogging.level.cn=DEBUG

2.2 分包

这里写图片描述

2.3 编写代码

entity

public class Student {    private int id;    private String name;    private String idCard;    private int age;    // 省略getter、setter}

Service

@Servicepublic class StudentService {    @Autowired    private StudentDao studentDao;    public List<Student> findList(){        return studentDao.findList();    }    public Student getById(int id){        return studentDao.getById(id);    }}

Controller

@RestController@RequestMapping(value = "/student")public class StudentController {    @Autowired    private StudentService studentService;    @GetMapping(value = "/list")    public List<Student> findList(){        return studentService.findList();    }    @GetMapping(value = "/getById/{id}")    public Student getById(@PathVariable int id){        return studentService.getById(id);    }}

dao

@Mapperpublic interface StudentDao {    List<Student> findList();    Student getById(@Param("id") int id);}

mapper

<mapper namespace="cn.yuan.dao.StudentDao">    <sql id="Base_Column_List">        id AS 'id',        id_card AS 'idCard',        name AS 'name',        age AS 'age'    </sql>    <select id="findList" resultType="Student">        select        <include refid="Base_Column_List" />        from student    </select>    <select id="getById" resultType="Student">        SELECT        <include refid="Base_Column_List" />        FROM student        WHERE id = ${id}    </select></mapper>

2.4 把项目跑起来看看

直接访问127.0.0.1:8080/student/list就可以看到结果
这里写图片描述

这样就完成了对Mybatis的整合,项目传到osgit,unit2-1上了