欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot整合Mybatis

程序员文章站 2022-06-05 16:06:27
...

我们引入上一章节的Druid配置文件,并且建立两张表,如下所示:
SpringBoot整合Mybatis
SpringBoot整合Mybatis
当然,我们也可以写一个sql文件,再用深入理解springboot(5)的方法,也能得到同样的结果。

我们建立两个bean——>Department and Employee

public class Department {

    private Integer d_id;
    private String d_name;

   ....省去get/set
}

public class Employee {
    private Integer id;
    private String lastname;
    private String email;
    private Integer gender;
    private Integer d_id;

    ....省去get/set
}

然后建立一个mapper.DepartmentMapper

@Mapper
public interface DepartmentMapper {
    @Select("select * from department where d_id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where d_id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "d_id")//告诉注解版的mybatis【department】对象中的id为自增主键
    @Insert("insert into department(d_id, d_name) values(#{d_id},#{d_name})")
    public int insertDept(Department department);

    @Update("update department set d_name=#{d_name} where d_id=#{d_id}")
    public int updateDept(Department department);
}

最后,再安排一个Controller.DeptController

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/dept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
}

当然,为了方便起见(其实也没方便什么!!),我们可以去掉@Mapper ,用一个@MapperScan加到启动类上面,相当于指定给 mapper包下面的所有的类都加上@Mapper一样,批量扫描所有的接口:

@MapperScan(value = "com.king.mybatis.mapper")
@SpringBootApplication
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

还有XML配置的方法,这个之前学过,就不再赘述。