SpringBoot学习04--使用MyBatis-Plus

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

我们接上一篇SpringBoot学习03–使用MyBatis的Generator生成代码,将其改成使用MyBatis-Plus的。

1.pom.xml引用 mybaits-plus

mybatis-spring-boot-starter替换成mybatis-plus-boot-starter,完整pom.xml如下:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.1.6.RELEASEversion>
		<relativePath/> 
	parent>
	<groupId>com.examplegroupId>
	<artifactId>demoartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>demoname>
	<description>Demo project for Spring Bootdescription>

	<properties>
		<java.version>1.8java.version>
	properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starterartifactId>
		dependency>
		<dependency>
			<groupId>com.baomidougroupId>
			<artifactId>mybatis-plus-boot-starterartifactId>
			<version>3.1.2version>
		dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
		<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>druid-spring-boot-starterartifactId>
			<version>1.1.10version>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>
	dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>
project>

2.修改 application.yml文件中的mybatis配置

# datasource config
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: admin123
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
# mybatis config
mybatis-plus:
  mapper-locations: classpath:mappers/*.xml
  type-aliases-package: com.example.demo.model
  global-config:
    db-config:
      id-type: auto

3.修改 AccountMapper.java文件

修改AccountMapper接口,使其继承 BaseMapper,如下

package com.example.demo.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.model.Account;
import org.springframework.stereotype.Repository;

@Repository
public interface AccountMapper extends BaseMapper<Account>{

}

通过查看BaseMapper接口,我们可以看到,它里面定义了通用的增删查改方法,这些方法方便了我们的使用。
SpringBoot学习04--使用MyBatis-Plus_第1张图片

4.修改Account类

增加注解@TableName("tb_account")
SpringBoot学习04--使用MyBatis-Plus_第2张图片

你可能感兴趣的:(Spring,Boot,学习)