整合springboot+mybatis时,本来什么都没配置,直接用的注解开发如:
/**
* @Description User映射类
* @Author xg
* @Date 2018/9/15 12:15
*/
@Mapper
public interface UserMapper {
@Select("SELECT * FROM sys_user WHERE name = #{name}")
User findUserByName(@Param("name") String name);
@Insert("INSERT INTO sys_user(name,login_name,password,email) VALUES(#{user.name}, #{user.login_name}, #{user.password}, #{user.email})")
int insert(@Param("user") User user);
@Select("SELECT * FROM sys_user")
List<User> findAll();
}
可以正常执行,但是想重新熟悉一下mybatis的xml配置文件方式,于是就搞起。
一切妥当,运行也没报错,但是执行接口报了一下异常:
原信息:
2018-09-20 14:46:14.321 [http-nio-8099-exec-8] ERROR o.a.c.c.C.[.[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.demospringboot.mapper.UserMapper.usersList] with root cause
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.demospringboot.mapper.UserMapper.usersList
说是绑定失败,在网上查了一些,例如:在application.yml文件中加
mybatis:
config-locations: classpath*:mapper/**Mapper.xml
尝试后发现无效,问题应该不仅仅如此。
又在pom.xml文件中加入
<!-- 资源 -->
<resources>
<resource>
<filtering>false</filtering>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<!--<filtering>false</filtering>-->
<directory>src/main/resources</directory>
</resource>
</resources>
结果依然无效,我在想是在之前配置mybatis时好像少了些什么,在网上找到加入mybatis配置类:
package com.demospringboot.configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
/**
* @Description mybatis配置
* @Author xg
* @Date 2018/9/20 14:38
*/
@Configuration
public class MybatisConfig {
@Autowired
private DataSource dataSource;
@Bean(name="sqlSessionFactory")
public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws IOException {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
Resource[] resources = new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/*Mapper.xml");
sessionFactory.setMapperLocations(resources);
return sessionFactory;
}
}
再次运行,成功解决!