Home Tags Posts tagged with "报错"

报错

Springboot整合Mybatis的步骤:

1.数据源配置:在application.properties里面

#配置数据源
spring.datasource.url=jdbc:mysql://localhost:3306/transactional_springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456789
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

2.(前提是导入依赖)实体类,Mapper接口的编写

@Repository
public interface UserMapper {
    void insertUser(User user);
}
@Data
@Repository
public class User {
    private String name;
    private int id;
}

3.Mapper.xml文件编写

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.yang.mapper.UserMapper">

    <insert id="insertUser" parameterType="com.yang.pojo.User">
          insert into  user(id,name) values (#{id},#{name});
    </insert>
</mapper>
4.Controller层编写
@RestController
public class InsertUserController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    User user;
    @PostMapping("/insert")
    public void insert(){
        user.setId(10);
        user.setName("First");
        userMapper.insertUser(user);
    }
}
5.测试类编写
@SpringBootTest(classes = Application.class)
public class Test {

    @Autowired
    InsertUserController insertUserController;

    @org.junit.jupiter.api.Test
    public void go(){
        insertUserController.insert();
    }
}

坑点:Mapper接口文件不仅要有@Repository注解(标记为Bean,给Spring管理)还要有@Mapper注解才可 !!!否则会报
Field userMapper in com.yang.controller.InsertUserController required a bean of type 'com.yang.mapper.UserMapper' that could not be found.
找不到Mapper文件错误