1、项目是在eclipse上用maven构建的,采用Dao与xml映射的形式
<!-- spring boot基本环境 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<!--web应用基本环境依赖 包含 Tomcat 和 spring-mvc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--MySql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--MyBatis 包含 spring-boot-starter-jdbc -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
2、项目结构
3、添加 @MapperScan({"com.xhl.springboot_1.dao"})
配置Dao的接口所在包名(在启动类或配置类)
package com.xhl.springboot_1;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
@MapperScan({"com.xhl.springboot_1.dao"})
public class Application
{
public static void main( String[] args )
{
SpringApplication.run(Application.class,args);
}
}
配置错误启动会报如下错误
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userMapper in com.xhl.springboot_1.service.impl.UserServiceImpl required a bean of type 'com.xhl.springboot_1.dao.UserMapper' that could not be found.
Action:
Consider defining a bean of type 'com.xhl.springboot_1.dao.UserMapper' in your configuration.
4、添加 mybatis.mapperLocations=classpath:**/mapper/*.xml
application.propertirs或(yml)中配置Dao的实体类所在位置
注意 propertirs文件和yml文件写法在格式上的区别
# --- {MyBatis} RDB JDBC Connection
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver
mybatis.mapperLocations=classpath:**/mapper/*.xml
如果*.xml与dao的接口类*.java在同一个包下(即相同路径),这块不进行配置也可以正确运行,否则虽然项目会正常启动,但是在请求数据时,dao会找不到xml,错误信息如下
控制台 org.apache.ibatis.binding.BindingException 异常
页面效果