Spring Boot框架 - 数据访问 - 整合Mybatis
一、新建Spring Boot项目
注意:创建的时候勾选Mybatis依赖,pom文件如下
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
二、配置文件application.properties中配置数据库信息
三、创建两个表(Employee,Department)
四、创建JavaBean 用来封装表的数据
五、使用mybatis对数据库进行操作
- 配置文件方式
- 在resources目录下新建目录:
- mybatis-config.xml 内容如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
- EmployeeMapper.xml 内容如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--将EmployeeMapper的全类名(右键复制相对路径)复制出来,放在namespace里面--> <mapper namespace="com.demo.springboot.mapper.EmployeeMapper"> <!--将接口的方法配置到映射文件中 id="方法名" resultType="返回值类型Employee的全类名"--> <select id="getEmpById" resultType="com.demo.springboot.bean.Employee"> select * from Employee where id=#{id}; </select> </mapper>
- 将EmployeeMapper接口的方法配置在映射文件EmployeeMapper.xml中
在application.properties 中添加配置
#mybatis配置 mybatis.config-location=classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
- 运行后测试(同下面的注解版 “***测试:新增一个Controller.DeptController”)
- mybatis-config.xml 内容如下
- 注解版方式
- 创建包:mapper
- 在包下添加一个接口:DepartmentMapper
/** * 指定这是一个操作数据库的mapper */ @Mapper public interface DepartmentMapper { @Select("select * from Department where id=#{id}") public Department getDeptById(Integer id); @Delete("delete from Department where id=#{id}") public int deleteDeptById(Integer id); @Insert("insert into Department(departmentName) values=(#{departmentName})") public int insertDept(Department department); @Update("update Department set departmentName=#{departmentName} where id=#{id}") public int updateDept(Department department); }
- ***测试:新增一个Controller.DeptController
@RestController public class DeptController { @Autowired DepartmentMapper departmentMapper; //查询,带入浏览器中的参数id @GetMapping("dept/{id}") public Department getDepartment(@PathVariable("id") Integer id){ return departmentMapper.getDeptById(id); } //插入 @GetMapping("dept/add") public Department addDepartment(Department department){ departmentMapper.insertDept(department); return department; } }
测试结果:
测试查询:在浏览器输入地址 http://localhost:8080/dept/1
- 测试插入:http://localhost:8080/dept/add?departmentName=%E6%8A%80%E6%9C%AF%E9%83%A8&empNum=13 查看数据库,新增数据成功