1、在pom.xml中加入jdbc、mybatis和mysql的坐标,如果使用IDEA工具快速构建,则会自动导入以下坐标
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2、数据源的配置,以下使用的是application.yml配置文件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.1.155/mybatis
driver-class-name: com.mysql.jdbc.Driver
3、定义一个接口,用于数据访问操作,在该接口上,添加上@Mapper注解,指明这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id = #{id}")
public Department getDepartmentById(Integer id);
@Select("select * from department")
public List<Department> getAll();
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDepartment(Department department);
@Delete("delete from department where id=#{id}")
public int deleteDepartment(Integer id);
@Update("update department set departmentName = #{departmentName} where id = #{id}")
public int updataDepartment(Department department);
}
4、在对应的方法上面写上相应的注解,表明进行什么样的数据操作
5、在controller中,将mapper自动注入,方便调用
@RestController
public class DepartmentController {
@Autowired
DepartmentMapper departmentMapper;
@GetMapping("/dept/all")
public List<Department> getAll(){
return departmentMapper.getAll();
}
}
以上便是通过注解来进行mybatis的相关操作。