mybatis注入mapper的三种方式和spring整合mybatis的错误

时间:2024-05-30 15:56:20

今天在学习Spring整合MyBatis的时候通过配置文件读取映射时出现了错误

报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): mapper.OrderMapper.getOrderList

解释:这个错误就是说Mapper接口被Spring注入后,没法读取到mapper.xml

 

然后mapper注入方式有三种:

第一种 相对于类路径的资源

<mapper resource=”sqlmap/User.xml”/> 直接对应相关的配置文件,不会报错,前提是namespace没写错

第二种 使用mapper接口类路径

  <mapper class=”mapper.UserMapper”/>

这种方法要求mapper接口名和mapper映射文件名称相同,放在一个目录中.

  这个也是注意要把namespace的路径对应接口路径,然后两文件同名放在一个目录下.

第三种 指定包下所有mapper接口, 配置完读取interface.class时就读取.xml文件了

  <mapper package=”mapper”/>

       这个和第二种类似,方法一样,是最常用的方法.

然后回到错误:

 1.检查mapper和mapper.xml是不是在一个包下,名字是不是一样  

mybatis注入mapper的三种方式和spring整合mybatis的错误

 2.Mapper.xml的namespace是否和mapper接口报名一样.

mybatis注入mapper的三种方式和spring整合mybatis的错误

 

3.检查方法名和sql的id是否一致

 

4.如果是maven项目(我的错误就是这个),因为maven默认是不编译xml文件的,所以运行完找不到报错,所以得在<build></build>里面加上

<resources>  

    <resource>  

        <directory>src/main/java</directory>  

        <includes>  

            <include>**/*.xml</include>  

        </includes>  

        <filtering>true</filtering>  

    </resource>  

</resources>  

5.配置完我还有个别的错误,

java.lang.ExceptionInInitializerError

Caused by: org.apache.ibatis.exceptions.PersistenceException:

### Error building SqlSession.

### The error may exist in mapper/OrderMapper.xml

### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.binding.BindingException: Type interface mapper.UserMapper is already known to the MapperRegistry.

       at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26)

       at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:82)

       at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:66)

       at utils.SqlSessionFactoryUtils.<clinit>(SqlSessionFactoryUtils.java:19)

       ... 23 more

Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.binding.BindingException: Type interface mapper.UserMapper is already known to the MapperRegistry.

       at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:109)

       at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:92)

       at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)

       ... 25 more

  如果你使用包扫描的话,就别在通过别的方式读取配置文件了,要不然会报错

mybatis注入mapper的三种方式和spring整合mybatis的错误