SpringBoot集成Mybatis步骤和问题整理
1.集成Mybatis
1.1 添加mybatis起步依赖和数据库驱动
<!--Mybatis起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--数据库驱动坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
1.2 配置数据库信息
配置resources下application.properties文件
注意:因为我用的是mysql 8.0.21版本,所以信息要改成
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
#数据库连接信息
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
1.3 建立相应的表和实体类
目录示意
建立domain包下创建实体类
/**
* 账户实体类
*/
public class Account {
private int id;
private int uid;
private double money;
//getter和setter方法省略
}
1.4 建立mapper下AccountMapper
@Component
@Mapper
public interface AccountMapper {
public List<Account> queryAccountList();
}
1.5 配置Mapper映射文件
<?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" >
<mapper namespace="com.jjp.mapper.AccountMapper">
<select id="queryAccountList" resultType="account">
SELECT * FROM account;
</select>
</mapper>
1.6 配置Mybatis信息
配置resources下application.properties文件
#配置mybatis信息
#pojo别名扫描包
mybatis.type-aliases-package = com.jjp.domian
#加载mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
1.7 编写controller
/**
* Controller层
*/
@Controller
public class AccoutController {
@Autowired
private AccountMapper accountMapper;
@RequestMapping("/account")
@ResponseBody
public List<Account> find(){
List <Account> accouts = accountMapper.queryAccountList();
return accouts;
}
1.8 运行结果
2.遇到的问题整理
2.1 @Mapper 报错 找不到
解决方法:检查pom引入是否正确
mybatis-spring-boot-starter
2.2 报错
方法1:在mapper文件上加@Repository注解,这是从spring2.0新增的一个注解,用于简化 Spring 的开发,实现数据访问 。
方法2:在mapper文件上加@Component注解,把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""。
(在一个博客下一位哥们的评论下看到的,试了方法二,成功解决,整理一下)
@Component
@Mapper
public interface AccountMapper {
public List<Account> queryAccountList();
}
2.3 网页404
原因:
IDEA目录结构的问题,Application启动类的位置不对.要将Application类放在最外侧,即包含所有子包 。而一开始我的controller则放在了最外层的包里面。
解决方法1,移动SpringbootMybatisApplication位置,使其位于最外层。
解决方法2,添加@SpringBootApplication(scanBasePackages=“controller”)