Bootstrap

springboot+mybatis plus框架下进行增删改查操作

框架搭建完成后,假设要对teacher表进行增删查改:

第一步

创建一个Teacher的POJO类

用注解指定该类对应的数据表

@TableName("teacher")
public class Teacher {...}

如果id字段为自增还需要用注解标明

@TableId(value = "tecid",type = IdType.AUTO)
private Integer tecid;

然后把所有涉及到增删查改操作的属性声明并且设置getter/setter

第二步

创建对应Dao接口并用@Repository注解标注,继承BaseMapper<Teacher>

@Repository
public interface TeacherDao extends BaseMapper<Teacher> {}

第三步

创建对应的Service接口,在Service接口中声明需要对数据进行操作的方法

public interface TeacherService {
    
    int insertTeacher(Teacher teacher);

    int updateTeacher(Teacher teacher);

    List<Teacher> selectTeacherList(Teacher teacher);

    Page<Teacher> selectTeacherByPage(Teacher teacher, long pageNum, long pageSize);

    Teacher selectTeacherById(Integer teacherId);
}

第四步

创建一个Service的实现类,并将所有方法实现。

@Service,表示这个为业务层

@Autowired注解是把这个对象自动注入到IOC容器中

部分关键代码:

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherDao teacherDao;

    @Override
    public int insertTeacher(Teacher teacher) {...}

    @Override
    public int updateTeacher(Teacher teacher) {...}

    @Override
    public List<Teacher> selectTeacherList(Teacher teacher) {...}

    @Override
    public Page<Teacher> selectTeacherByPage(Teacher teacher, long pageNum, long pageSize) {...}

    @Override
    public Teacher selectTeacherById(Integer teacherId) {...}

第五步

写一个Controller类,把拿到的数据输出到要显示的页面上

在类上用@RestController注解表明这是Controller层

@Api(tags = "teacher案例接口")
@RestController
@RequestMapping("/teacher")
public class TeacherController {...}

示例方法:

根据"tectitle"字段查询一个教师的详细信息

@ApiOperation("查询teacher列表案例")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tectitle", value = "传递字符串")
    })
    @GetMapping("/list")
    public ListMessage<Teacher> selectTeacherList(Teacher teacher){
        ListMessage<Teacher> listMessage = new ListMessage<>();
        List<Teacher> list = teacherService.selectTeacherList(teacher);
        if (list != null) {
            listMessage.setDatalist(list);
            listMessage.setCode(1);
        } else {
            listMessage.setCode(0);
            listMessage.setMsg("没有查询到数据");
        }
        return listMessage;
    }

第六步

开启运行类后,这里用的是swagger,端口号设置为默认的80,访问下面的网址就可以进行测试了

http://127.0.0.1/swagger-ui.html

网页示例:

;