使用Mybatis自定义mapper.xml-遇坑Invalid bound statement
使用Mybatis自定义mapper.xml-遇坑Invalid bound statement
最近在使用Mybatis时,需要用到自定义mapper.xml,但是当我把mapper类和xml文件都准备好了,做单元测试的时候一直报错,如下:
再从头开始检查下,看看哪里不对
InsuranceBeneficiaryMapper.xml文件如下:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 4 <mapper namespace="com.yupao.insurance.service.dao.mapper.InsuranceBeneficiaryMapper"> 5 <select id="selectAll" resultType="com.yupao.insurance.service.dao.entity.InsuranceBeneficiaryDO"> 6 select * 7 from insurance_beneficiary_list; 8 </select> 9 </mapper>
InsuranceBeneficiaryMapper.java文件如下:
1 package com.yupao.insurance.service.dao.mapper; 2 3 import org.springframework.stereotype.Repository; 4 5 import com.baomidou.mybatisplus.core.mapper.BaseMapper; 6 import com.yupao.insurance.service.dao.entity.InsuranceBeneficiaryDO; 7 8 import java.util.List; 9 10 @Repository 11 public interface InsuranceBeneficiaryMapper extends BaseMapper<InsuranceBeneficiaryDO> { 12 List<InsuranceBeneficiaryDO> selectAll(); 13 }
单元测试代码如下:
1 package com.yupao.test; 2 3 import com.yupao.insurance.service.dao.entity.InsuranceBeneficiaryDO; 4 import com.yupao.insurance.service.dao.mapper.InsuranceBeneficiaryMapper; 5 import com.yupao.web.Application; 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.boot.test.context.SpringBootTest; 10 import org.springframework.test.context.junit4.SpringRunner; 11 12 import java.util.List; 13 14 @SpringBootTest(classes = Application.class) 15 @RunWith(SpringRunner.class) 16 public class AgreementDaoTest { 17 18 @Autowired 19 private InsuranceBeneficiaryMapper beneficiaryMapper; 20 21 @Test 22 public void testStatistics() { 23 List<InsuranceBeneficiaryDO> insuranceBeneficiaryDOS = beneficiaryMapper.selectAll(); 24 System.out.println(insuranceBeneficiaryDOS); 25 } 26 }
反复排查,始终报错:Invalid bound statement ,意思就是找不到绑定的mapper.xml文件,但是明明就有啊,如下图:
最后,终于找到原因:resources下面的路径不对,而在idea左侧目录下是看不出来问题的,如果仔细一点,打开文件所在电脑的目录或者在idea顶部窗口下就能看出其真实的文件目录:
原来是这样,之前我们看到的那个目录是单个文件夹的名称就有这么长,并没有分成多个目录!!!
我们再点击右键,重新创建目录 /com/yupao/insurance/service/dao/mapper,然后看到的就是下面这个目录结构:
再跑一下测试代码:
这下就能成功运行了!