最近学习springboot的整合mybatis中
遇到mapper不能注入成功,在网上上找了2天, 也没能解决
我自己关注过的信息有:
- 注意目录结构,所有代码要放到DemoApplication类的同级或者下级目录
- StudentMapper.xml文件放到resources, 或者跟StudentMapper.java (interface文件)同一个目录
先弄一个错误案例供分析,此案例是把mapper的xml放到resources目录中的
求各位解惑,感谢了
以下是报告错误:
Description:
Field studentMapper in com.example.demo.service.imp.StudentServiceImpl required a bean of type 'com.example.demo.mapper.StudentMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.mapper.StudentMapper' in your configuration.
主要参照一下两篇文章:
SpringBoot框架:https://blog.csdn.net/friggly/article/details/123888590
Mybatis之逆向工程生成代码(简单容易上手): https://blog.csdn.net/xiaoheihai666/article/details/125664202
利用逆向生成代码之后,目录结构如图:
application.properties 文件内容:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapper-locations=classpath:mapper/*.xml
StudentServiceImpl.java 文件如下:
package com.example.demo.service.imp;
import com.example.demo.mapper.StudentMapper;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student queryStudentById(Integer id) {
return null;
}
}
StudentMapper.java 文件内容:
package com.example.demo.mapper;
import com.example.demo.model.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentMapper {
int deleteByPrimaryKey(Integer id);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
}
StudentMapper.xml的截图: