SpringBoot整合Mybatis plus使用遇到的问题
前言:
SpringBoot确实是个好东西,帮我们整合了市面上大部分的框架,提供了很简便的使用方式。
Mybatis plus一款针对Mybatis的增强产品,让Mybatis用起来更加的方便。
具体的学习大家可以去官网查看,有使用过Mybatis和JPA的或者SpringData的基本上看一遍就会了。
这是官网:https://mp.baomidou.com/guide/
==============开始=================
因为只是学习,所以只是个简单的Demo,能运行就可以。
添加依赖:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--Mybatis plus start--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.0</version> </dependency> <!--Mybatis plus end--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency>依赖主要就是数据库驱动,springboot整合mybatis-plus和swagger的依赖,其他的就是SpringBoot的一些基本依赖就不放出来。
然后对数据库简单配置一下,就是驱动,数据库用户名和密码这些。
datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/ username: root password: 123456
实体类是数据库保持一致就好了
@Data @ApiModel(value = "作者实体类") @Accessors(chain = true) public class Author implements Serializable { @ApiModelProperty(hidden = true) private Integer authorId; @ApiModelProperty(name = "authorName", value = "作者名", required = true) private String authorName; }
这里提一下,相信用过Mybatis的一定用过他的逆向生成工具对吧,所以Mybatis-plus也延续了这个方法,而且更加强大,可以从mapper层到service层和controller层都可以生成,当然也包括实体类和XML配置,这里我没有用他的代码生成器,Mybatis-plus直接取名叫代码生成器了,确实很厉害。
下面是Mapper层和Service层以及Controller层,都很简单,Mybatis-plus对Mapper提供了BaseMapper,对Service提供了IService和ServiceImpl,这就像是JPA的使用方式,继承就好了,基本的CRUD都已经提供了。
@Mapper public interface AuthorDao extends BaseMapper<Author> { }
@Service("authorService") public class AuthorServiceImpl extends ServiceImpl<AuthorDao,Author> implements AuthorService { }
public interface AuthorService extends IService<Author> { }
/** * @Author: Sakura * @Description: * @Date: 2019/3/12 16:05 */ @RestController @RequestMapping("/author") @Api(description = "作者管理接口") public class AuthorController { @Autowired private AuthorService authorService; @GetMapping("/{id}") @ApiOperation(value = "通过id查找作者") public Author getById(@PathVariable("id") Integer id){ final Author author = authorService.getById(id); System.out.println("====" + author); return author; } @PostMapping public String insert(Author author) { final boolean save = authorService.save(author); System.out.println(save); return "success"; } }
搞定直接开始测试。
我们先添加一条数据
数据库是有的,说明没有问题。
然后下面再测试getById方法,插一下,save和getById这些方法都是service接口提供的不是我们自己写的啊。
没有看到结果,但是控制台也没有报错,获取到的数据是null
然后看了下sql,发现sql的where后面接的居然是null
也就是说这玩意读取到其他字段,但是没有读取到主键是什么。
这就是个坑,因为我没有用他的代码生成器,实体类是自己建的,所以少了一个标明主键的注解
@TableId(type = IdType.AUTO)
如果是自动生成的,那么实体类的主键上就会有这个注解,这个问题浪费我太多时间,因为也是才开始接触Mybatis-plus,所以犯了个这么不大不小的错,特此记录一下,也记录一下基本的操作方式。
bye~