“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天,点击查看活动详情
mybatis-generator的使用
搭建环境
- 新建一个空的项目
新建一个空项目,建基础包
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文件
配置连接的数据库信息,以及生成的实体类所在的包的位置
配置mapper文件所在的包的位置
- 数据库中建表
在数据库中新建已一个rank
表
- 执行mybatis_generator
双击红框位置
执行成功,可以看到自动生成了RankMapper
、Rank
、RankExample
、RankMapper.xml
四个文件
简单操作
可以看到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语句操作。