Bootstrap

SpringBoot_mybatis-plus基础使用

前言

  • springboot + mybatis-plus整合
  • 连接mysql数据库

快速开始

maven依赖

  1. 引入 Spring Boot Starter 父工程
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.18.RELEASE</version>
        <relativePath/>
    </parent>
  1. 引入mybatis-plus-boot-starter和mysql数据库驱动包
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <!-- mybatis-plus-->
        <mybatis-plus-boot-starter.version>3.4.2</mybatis-plus-boot-starter.version>
        <!-- mysql-->
        <mysql-connector-java.version>8.0.18</mysql-connector-java.version>
    </properties>

        <!--mysql jdbc驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>

application.yaml配置

server:
  port: 8888
spring:
  datasource:
    #driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.100.70:3306/demo_redis?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
    username: root
    password: 123456

@MapperScan注解扫描启动

新建MybatisPlusConfig配置类, 添加一般都会使用的分页拦截器

@Configuration
@MapperScan("com.myron.demo.mapper")// 扫描mapper路径
public class MybatisConfig {

	/**分页拦截器*/
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //如果有多数据源可以不配具体类型 否则都建议配上具体的DbType
        //interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

基础使用

数据库表生成推荐使用liquibase 版本化方式来管理表,生命周期. 既记录的过程版本,也方便更换数据库.

传送门:SpringBoot_liquibase使用

业务代码

  1. 实体对象
/**
 * account账号对象
 */
@TableName("account")
public class Account implements Serializable{
	private static final long serialVersionUID = 1L;

	/** 用户ID*/
	@ApiModelProperty(value="用户ID")
	@TableId(type = IdType.AUTO)
	private String id;

	/** 用户名*/
	@ApiModelProperty(value="用户名")
	private String username;

	/** 姓名*/
	@ApiModelProperty(value="姓名")
	private String name;

	/** 密码*/
	@ApiModelProperty(value="密码")
	private String password;

	/** 性别*/
	@ApiModelProperty(value="性别")
	private String sex;

	/** 手机*/
	@ApiModelProperty(value="手机")
	private String phone;

	/** 邮件*/
	@ApiModelProperty(value="邮件")
	private String email;

	/** 创建时间*/
	@ApiModelProperty(value="创建时间")
	private Date createTime;

	/** 创建时间*/
	@ApiModelProperty(value="修改时间")
	private Date updateTime;
	
	//setter/getter方法省略
}
  1. mapper对象
public interface AccountMapper extends BaseMapper<Account>{

}
  1. service
public interface AccountService {
	void createUser(Account account);
	void updateUser(Account account);
	void deleteUser(Account account);
	Account findUserByPrimaryKey(String userId);
	List<Account> findList(Account account);
	Page<Account> findListByPage(Account account, Page<Account> page);
}

  1. serviceImpl
@Service("userService")
@Transactional(rollbackFor=Exception.class)
public class AccountServiceImpl implements AccountService {
	private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);
	
	@Autowired
	private AccountMapper accountMapper;
	
	@Override
	public void createUser(Account account) {
		Date currentTime = new Date();
		account.setCreateTime(currentTime);
		account.setUpdateTime(currentTime);
		this.accountMapper.insert(account);
	}
	
	@Override
	public void updateUser(Account account) {
		this.accountMapper.updateById(account);
	}

	@Override
	public void deleteUser(Account account) {
		this.accountMapper.deleteById(account.getId());
	}

	@Override
	public Account findUserByPrimaryKey(String userId) {
		return this.accountMapper.selectById(userId);
	}

	@Override
	public Page<Account> findListByPage(Account account, Page<Account> page) {
		return this.accountMapper.selectPage(page, new QueryWrapper<>());
	}

	@Override
	public List<Account> findList(Account account){
		return this.accountMapper.selectList(new QueryWrapper<>(account));
	}

}`

  1. controller
@Api(tags="account账号信息api接口")
@RestController
@RequestMapping("/account")
public class AccountController {

	@Autowired
	private AccountService accountService;

	@ApiOperation(value="分页查询--账号信息")
	@GetMapping(value = "/page")
	public ApiResult<PageInfo<List<Account>>> listByPage(Account account, PageInfo pageParam) {
		Page<Account> page = this.accountService.findListByPage(account, new Page(pageParam.getPageIndex(), pageParam.getPageSize()));
		return PageResult.wrapPage(page);
	}

	@ApiOperation(value="添加--账号信息")
	@PostMapping(value = "/add")
	public ApiResult<Account> add(@RequestBody Account account) {
		return new ApiResult<>(this.accountService.createAccount(account));
	}

	@ApiOperation(value="修改--账号信息")
	@PutMapping(value = "/edit/{id}")
	public ApiResult<Account> edit(@RequestBody Account account, @PathVariable("id") long id)  {
		account.setId(id);
		return new ApiResult<>(this.accountService.updateAccount(account));
	}

	@ApiOperation(value="删除--账号信息")
	@DeleteMapping(value = "/delete/{id}")
	public ApiResult<Void> delete(@PathVariable("id") long id) {
		Account param = new Account();
		param.setId(id);
		this.accountService.deleteAccount(param);
		return new ApiResult<>();
	}

}

开始使用

进阶–拦截器使用

高级–@MapperScan原理

TODO

常见错误汇总

  1. Mybatis 操作表中包含MySQL关键字导致报错

参考文档

  1. 官网–快速开始
;