mybatis-plus的使用心得和天坑

174 阅读1分钟

依赖pop(必须装且版本不冲突!!!!!十分重要)


<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId>  
</dependency>
<dependency>  
    <groupId>com.baomidou</groupId>  
    <artifactId>mybatis-plus-boot-starter</artifactId>  
    <version>3.5.3</version>  //一定要3.5.3以上否则报错!!!!!!!!!!!!!重点
</dependency>
<dependency>  
    <groupId>org.mybatis</groupId>  
    <artifactId>mybatis</artifactId>  
    <version>3.5.6</version>  
</dependency>

版本低于3.5.3报错

mybatis-plus-failway.PNG Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'userMapper': Error creating bean with name 'UserMapper' defined in file [D:\ideaProjectAll\springboot-demo-vue\target\classes\com\example\springbootdemovue\mapper\UserMapper.class]: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

配置数据库

server:  
    port: 9090  
  
spring:  
    datasource:  
        driver-class-name: com.mysql.cj.jdbc.Driver  
        url:jdbc:mysql://localhost:3306/sys_useruseUnicode=true&characterEncoding=utf-8  
        username: root  
        password: 自己的密码
        
mybatis:  
#扫描xml文件,告诉spring什么是mapper .xml  
    mapper-locations: classpath:mapper/*.xml  
#打印sql语句  
    configuration:  
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  
mybatis-plus:  
    configuration:  
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

启动类配置

@MapperScan("com.example.springbootdemovue.mapper") //mapper文件包

实体类

@Data  
@NoArgsConstructor  
@AllArgsConstructor  
//利用mybatis-plus 查询 需要实体类和表同名,这里也要注意!!!!!!!!
@TableName(value = "user")  
public class User {  
@TableId  
private Integer id;  
  
private String username;  
private String password;  
private String nickname;  
private String email;  
private String phone;  
private String address;  
}

编写mapper接口


public interface UserMapper extends BaseMapper<User> {

}

测试


@SpringBootTest
public class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.isTrue(5 == userList.size(), "");
        userList.forEach(System.out::println);
    }

}

注意

Could not autowire. No beans of 'UserMapper' type found.

private UserMapper usermapper;爆红

不用管不影响,也可以给mapper加上 @Component

@Component(value = "UserMapper")  
public interface UserMapper extends BaseMapper<User> {}