步骤:
1.添加mybatis依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2.在配置文件中配置数据源信息
application.properties文件
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/访问的数据库名称
spring.datasource.username=数据库的用户名
spring.datasource.password=数据库的密码
3.编写pojo (toString,getter,setter,全参无参构造) mapper接口 mapeer映射文件
控制层:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
//SpringBoot整合mybatis
@RequestMapping("/getMUserList")
public String getMUserList(Model model){
List<MUser> mUserslist = userMapper.getUserList();
model.addAttribute("muserList",mUserslist);
return "user";
}
}
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
//SpringBoot整合mybatis
@RequestMapping("/getMUserList")
public String getMUserList(Model model){
List<MUser> mUserslist = userMapper.getUserList();
model.addAttribute("muserList",mUserslist);
return "user";
}
}
mapper层:
public interface UserMapper {
List<MUser> getUserList();
}
List<MUser> getUserList();
}
mapper.xml(sql映射文件):
<?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="mapper接口的全类名">
<select id="getUserList" resultType="返回数据的类型">
select * from user
</select>
</mapper>
返回数据的类型:是列表时就返回List泛型(<>)元素类型
主启动类:添加注解
手动配置mybatis的包扫描:在主启动类添加@MapperScan
@MapperScan(basePackages = "com.offcn.mapper")
运行后
将sql映射文件和mapper接口放在一个包下,会出错:——报错org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.offcn.mapper.UserMapper.getUserList
解决办法:
方法一: 把映射(.xml)文件 放到resources 目录下 结构目录一模一样
方法二:pom文件中
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>