springboot测试mapper(mybatis)

  实体类:记得加@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);
    }

}
复制代码

 

posted @   爱编程DE文兄  阅读(4103)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示