springboot04-集成Mybatis

1、添加依赖

        <!--Mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--Mybatis整合Springboot框架的起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

2、修改配置文件

spring:
  profiles:
    active: dev
server:
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssmbuild
    username: root
    password: 2000820.

3、创建controller、mapper、pojo、service包。在resources下创建mapping包

4、创建数据库

DROP TABLE IF EXISTS t_student;
CREATE TABLE t_student(
	id INT(10) NOT NULL AUTO_INCREMENT,
	NAME VARCHAR(20) NULL,
	age INT(10) NULL,
	CONSTRAINT PK_T_STUDENT PRIMARY KEY clustered(id)
);

INSERT INTO t_student(NAME,age) VALUES("zhangsan", 25);
INSERT INTO t_student(NAME,age) VALUES("lisi", 28);
INSERT INTO t_student(NAME,age) VALUES("wangwu", 23);
INSERT INTO t_student(NAME,age) VALUES("Tom", 21);
INSERT INTO t_student(NAME,age) VALUES("Jck", 55);
INSERT INTO t_student(NAME,age) VALUES("Lucy", 27);
INSERT INTO t_student(NAME,age) VALUES("zhaoliu", 75);

5、创建实体类

public class Student {
    private int id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

6、创建对应的StudentMapper接口
(如果没有添加Mapper,需要在启动类中添加@MapperScan("com.study.springboot.mapper")来标明mapper的位置)

7、创建StudentMapping.xml文件

8、然后在application-dev.yml配置文件中,配置mapper.xml文件的位置
注意:如何mapper.xml文件放在了com.study.springboot.mapper文件中,就不需要配置这个(但是需要在启动类中写mapperscan注解,这样才会扫描到这个xml文件),但是需要在pom文件中配置过滤文件(因为扫描器只会扫描到.java文件,不会扫描.xml文件)

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.study.springboot.pojo

最后application-dev.yml文件如图所示

9、创建StudentService文件

10、创建StudentController文件

11、完成以上,下面在启动类里加上注解用于给出需要扫描的mapper文件路径@MapperScan("com.study.mapper")

12、成功启动

posted @ 2021-09-10 22:00  不是孩子了  阅读(36)  评论(0编辑  收藏  举报