1.在使用Mapper的xml文件时,报错
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.wangbin.springboot_docker.dao.UserDAO.save
解决:检查是否在resource下创建相应的mapper.xml,检查application.properties中的扫描路径是否写对。
我的application.properties:
spring.application.name=docker
server.port=8989
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.217.118:3306/test?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
mybatis.mapper-locations=classpath:com/wangbin/mapper/*.xml
mybatis.type-aliases-package=com.wangbin.springboot_docker.entity
logging.level.root=info
logging.level.com.wangbin.springboot_docker.dao=debug
注意mybatis.mapper-locations路径是否正确,我的mapper位置:
UserDAOMapper.xml:
<?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.wangbin.springboot_docker.dao.UserDAO">
<insert id="save" parameterType="com.wangbin.springboot_docker.entity.User" useGeneratedKeys="true" keyProperty="id">
insert into user values(#{id},#{name},#{birth})
</insert>
<select id="findAll" resultType="com.wangbin.springboot_docker.entity.User">
select id,name,birth from user
</select>
</mapper>
注意命名空间(namespace)
2.其他均正确,报错:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘com.wangbin.springboot_docker.TestUserDAO’: Unsatisfied dependency expressed through field ‘userDAO’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.wangbin.springboot_docker.dao.UserDAO’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
解决:在相应的DAO前加注解
@Mapper
public interface UserDAO {
void save(User user);
List<User> findAll();
}
另外,也可以不使用xml文件,使用注解:
@Mapper
public interface UserDAO {
@Insert("insert into user values(#{id},#{name},#{birth})")
void save(User user);
@Select("select id,name,birth from user")
List<User> findAll();
}
解决自动注入爆红问题:
在UserDAO接口前加@Component(value = “UserDAO”)