Java入门8:使用MyBatis-Plus查询数据

98 阅读1分钟

该文章是Java入门系列的第八章:使用MyBatis-Plus查询数据

查询数据

打开Controller.java文件,我们在里面获取数据库的数据,代码如下:

其中注解@Autowired表示自动接线,可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。我的理解就是他会自动去找Student类,Student映射,和数据库

package org.example;

import com.google.gson.Gson;
import org.example.mapper.StudentMapper;
import org.example.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class Controller {
    @Autowired
    StudentMapper studentMapper;

    private Gson gson = new Gson();
    @GetMapping("/select")
    public String selectStudentList () {
        List<Student> students = studentMapper.selectList(null);
        return gson.toJson(students);
    }
}

还需要在启动类Application.java中添加如下代码,在这里用到了mybatis,其中使用@MapperScan指定要变成实现类的接口所在的包:

package org.example;

import org.mybatis.spring.annotation.MapperScan; // 添加的代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("org.example.mapper") // 添加的代码
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

此时打开http://localhost:8080/test ,可以发现数据查询到并且返回成功了

image.png

写在最后

以上就是使用MyBatis-Plus查询数据的全部说明,下一章节介绍使用MyBatis-Plus删除数据