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);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM