项目案例
通过 SpringBoot +MyBatis 实现对数据库学生表的查询操作
实现步骤:
(1)准备数据库
- 创建新的数据库 springboot,指定数据库字符编码为 utf-8
(2)创建 004-springboot-mybatis 项目
(3)在pom.xml中添加相关的jar依赖
<!--MySql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--Mybatis整合SpringBoot框架的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
(4)在 Springboot 的核心配置文件 application.properties 中配置数据源
server.port=8080
server.servlet.context-path=/springboot
#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3366/springboot
spring.datasource.username=root
spring.datasource.password=123456
(5)利用Mybatis逆向工程生成数据库表的接口、映射文件以及实体类对象,具体可以看一下个人博客Mybatis的文章
(6)在 src/main/java/web 包下创建 StudentController 并编写代码
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/student")
@ResponseBody
public Object student(Integer id){
Student student = studentService.queryStudentById(id);
return student;
}
}
(7)在 service 包下创建 service 接口并编写代码
public interface StudentService {
/**
* 根据学生标识获取学生详情
* @param id
* @return
*/
Student queryStudentById(Integer id);
}
(8)在 service.impl 包下创建 service 接口实现类并编写代码
Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student queryStudentById(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}
}
(9)在Mybatis逆向工程中生成的StudentMapper接口上加一个Mapper注解
@Mapper作用:Mybatis自动扫描数据持久层的映射文件及Dao接口的关系
@Mapper//扫描Dao接口到spring容器中
public interface StudentMapper {
注意:
默认情况下,Mybatis的xml映射文件不会编译到target的class目录下,所以我们需要在pom.xml文件中配置resources
<!--手动指定文件夹为resources-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
(10)启动Application应用,在浏览器中输入网址测试
(11)如果映射文件比较多的时候,每一个Dao接口都需要配置一个注解就显得比较麻烦,这时可以在运行主类上添加注解包扫描器@MapperScan(" com.hcz.mapper")
- 注释掉StudentMapper接口上的@Mapper注解
- 在运行主类Application上加@MapperScan(“com.hcz.mapper”)
@SpringBootApplication
//开启扫描器,不用像上一个工程一样每一个Dao接口类都添加一个注解扫描器
@MapperScan(basePackages = "com.hcz.mapper")
public class Application {
或者
@SpringBootApplication
//开启扫描器,不用像上一个工程一样每一个Dao接口类都添加一个注解扫描器
@MapperScan( "com.hcz.mapper")
public class Application {
(12)将接口和映射文件分开
- 在 application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定
# 指定 Mybatis 映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml
(13)关于Mapper映射文件存放的位置的写法有两种:
(1)将Mapper接口和Mapper映射文件存放到src/main/java同一目录下,还需在pom.xml文件中手动指定资源文件夹路径resources
(2)将Mapper接口和Mapper映射文件分开存放
Mapper接口类存放到 src/main/java 目录下
Mapper映射文件存放到 resources目录下(类路径)
在springboot核心配置文件application.properties中指定mapper映射文件存放的位置