版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27828675/article/details/82084778
基本依赖不变,请参考Spring Boot入门教程-集成Mybatis
如果项目业务复杂,涉及到连表查询,或者要写复杂的SQL语句时,使用注解方式就变的不那么方便了,所以使用xml 方式就显示出了优越性,尤其mapper接口和xml及model 都可以通过工具生成。
先看一下项目结构:红框中是生成的model,mapper,xml 。
贴一下数据库建表语句
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4
controller:这里只是做测试,没有写service 层。
@RestController
public class MainController {
@Autowired
StudentMapper studentMapper;
@RequestMapping(value = "all")
public List<Student> getList(){
return studentMapper.getAll();
}
}
在Application 中添加@MapperScan注解
@MapperScan("com.xuweichao.mybatis.mapper")
@SpringBootApplication
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
}
启动使用Postman请求http://localhost:8080/all后报错:
{
"timestamp": "2018-08-26T13:44:15.089+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Invalid bound statement (not found): com.xuweichao.mybatis.mapper.StudentMapper.getAll",
"path": "/all"
}
意思是找不到映射文件中的getAll
<select id="getAll" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from student
</select>
查看编译后的代码发现xml 文件没有进去。
解决:在pom.xml build中添加resourc配置,这样一切迎刃而解。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>