以查询学生信息案例为例:
一、在pom.xml中添加依赖
<!--MySQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<version>5.1.9</version>-->
</dependency>
<!--MyBatis整合SpringBoot框架的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
二、配置信息
application.yml
# 配置数据库信息
spring:
datasource:
username: root
password: admin
# ?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
# 整合mybatis
mybatis:
# 可以取别名
type-aliases-package: com.cailearnjava.pojo
# 如果将mapper层的xml配置文件放在resource文件夹下
mapper-locations: classpath:mybatis/mapper/*.xml
三、mapper层
StudentMapper.java
// 这个注解表示了这是一个 mybatis 的 mapper 类
@Mapper
//此注解表明这是一个持久层组件
@Repository
public interface StudentMapoer {
Student getStudentById(int id);
}
配置文件:StudentMapper.xml
<mapper namespace="com.cailearnjava.mapper.UserMapper">
<select id="getStudentById" resultType="Student">
select * from springboot.student;
</select>
</mapper>
四、service层
接口文件StudentService.java
public interface StudentService {
/**
* 根据学生ID查询详情
* @param id
* @return
*/
Student getStudentById(int id);
}
接口实现类:StudentServiceImpl.java
//此注解表明这是一个服务层组件
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getStudentById(int id) {
return studentMapper.getStudentById(id);
}
}
五、controller层
StudentController.java
//此注解表明这是一个控制层组件
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/student")
public @ResponseBody Object student(Integer id) {
Student student = studentService.getStudentById(id);
return student;
}
}
六、项目入口文件
//关键注解,开启自动配置
@SpringBootApplication
//开启扫描Mapper接口的包以及子目录
@MapperScan("com.cailearnjava.mapper")
public class Springboot05MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot05MybatisApplication.class, args);
}
}
另外,如果mapper的xml配置文件和mapper接口文件放在同一个文件夹下,则要在pom.xml中加入下面代码:
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
这样,在项目编译的时候就会被扫描进相应的目录中。