实体类:记得加@Mapper注解,不需要在springboot主程序类上加@MapperScaner
@Mapper public interface StudentMapper { public void saveStudent(Student student); }
实体类对应的映射文件:请记得得加第二行的约束语句,好多人都是没加这个
<?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.aib.springmvc.mapper.StudentMapper"> <!-- 插入学生数据 --> <insert id="saveStudent" parameterType="com.aib.springmvc.bean.Student"> insert into stu values(#{name},#{age},#{sex}) </insert> </mapper>
数据源和mapper文件参数配置:好多人习惯了mapper接口和mapper配置放在同一目录下,都会忘了加上mapper.xml的路径了;还有数据源使用springboot默认就行了,想要使用其他数据源记得导依赖,并配置要使用的数据源
#\u914D\u7F6E\u6570\u636E\u6E90,yml\u683C\u5F0F spring: datasource: url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8 username: root password: 1223 driver-class-name: com.mysql.cj.jdbc.Driver #\u6307\u5B9Amybatis\u6620\u5C04\u6587\u4EF6\u7684\u5730\u5740 mybatis: mapper-locations: classpath:com/springmvc/mapper/xml/*.xml
测试类:这里使用@Autowired会提示有错误,但不影响执行
@SpringBootTest(classes = {SpringmvcDemoApplication.class}) @RunWith(SpringRunner.class) public class TestMapper { @Autowired private StudentMapper studentMapper; @Test public void test() { Student stu = new Student(); stu.setName("zhangsan"); stu.setAge(10); stu.setSex("男"); studentMapper.saveStudent(stu); } }