mybatis-generator的使用

155 阅读2分钟

“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天,点击查看活动详情

mybatis-generator的使用

搭建环境

  1. 新建一个空的项目 新建一个空项目,建基础包 企业微信截图_16596676051980.png

application.properties文件(配置数据库信息):

spring.datasource.properties.jdbc-url=jdbc:mysql://127.0.0.1:3306/%s?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true
spring.datasource.properties.database=test
spring.datasource.properties.username=root
spring.datasource.properties.password=123456
spring.datasource.properties.driver-class-name=com.mysql.cj.jdbc.MysqlDataSource

generatorConfig.xml文件

配置连接的数据库信息,以及生成的实体类所在的包的位置 企业微信截图_16596678344792.png 配置mapper文件所在的包的位置 企业微信截图_16596678923653.png

  1. 数据库中建表

在数据库中新建已一个rank企业微信截图_16596679592030.png

  1. 执行mybatis_generator

双击红框位置

企业微信截图_16596679986254.png

执行成功,可以看到自动生成了RankMapperRankRankExampleRankMapper.xml四个文件

企业微信截图_16596680545815.png

简单操作

可以看到RankMapper文件当中自动生成了11个方法,我们可以按需使用。

package com.example.test.dao;

import com.example.test.entity.Rank;
import com.example.test.entity.RankExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface RankMapper {
    long countByExample(RankExample example);

    int deleteByExample(RankExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Rank record);

    int insertSelective(Rank record);

    List<Rank> selectByExample(RankExample example);

    Rank selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Rank record, @Param("example") RankExample example);

    int updateByExample(@Param("record") Rank record, @Param("example") RankExample example);

    int updateByPrimaryKeySelective(Rank record);

    int updateByPrimaryKey(Rank record);
}

在实际的开发场景中,经常需要各种查询修改等操作,比如想要分页查询rank表的数据,并根据id升序排列

select * from rank order by id limit 0,20;

查询score在90-100之间的数据:

select * from rank where score<100 and score>90 order by id;

等等,这是在字段较少的情况下,就可以有多种查询需求,当字段较多场景复杂的时候,照这样写,肯定会有一个接一个的查询方法。
但现在可以使用自动生成的方法,下面举一个简单的例子:

public PageResponse<RankEntity> pageQueryRank(int pageNum, int pageSize,String name) throws Exception {
    RankExample example = new RankExample();
    RankExample.Criteria criteria = example.createCriteria();
    criteria.andNameEqualTo(name);
    example.setOffset((pageNum - 1) * pageSize);
    example.setLimit(pageSize);
    example.setOrderByClause("id desc");
    List<RankEntity> entities = rankDao.selectByExample(example);
    return new PageResponse<>((int) rankDao.countByExample(example), entities);
}

这样就会更灵活更方便,避免写很多的sql语句。当然对于更复杂的操作,还是需要自己去写sql语句操作。