MyBatis-Plus
1.1 MyBatis-Plus简介
官网:mybatis.plus ,MyBatis-Plus
作者:苞米豆 在Mybatis基础上只增强,不改变。
1.2 使用流程
POJO配置
@TableName("user")//指定表名,写在类上。
@TableId(type = IdType.NONE)//IdType设置主键生成策略
@TableField(select = false)//查询不返回该字段
@TableField(value = "email")//解决列名,属性不对应(别名)
@TableField(exist = false)//表中不存在该列。如果该字段不赋值,则不影响插入等操作,赋值,必须加注解。
Dao继承 BaseMapper,可以设置泛型,然后对数据进行操作(增删改查)
public interface UserDao extends BaseMapper<User>
编写相关代码进行测试
1.3 具体流程
导入相关依赖
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
配置 application.properties
#连接数据库
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql:///xxx?serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#mybatis-plus
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#用户自定义sql编写 *.xml 配置文件
#mybatis-plus.mapper-locations=classpath:mapper/*.xml
#配置实体类属性名和数据库字段名对应驼峰形式
#mybatis-plus.configuration.map-underscore-to-camel-case=true
#分页插件
pagehelper.helper-dialect=mysql
pagehelper.support-methods-arguments=true
pagehelper.reasonable=true
1.4CRUD操作
POJO
按照数据库来创建实体类并通过注解映射
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("tb_music")
public class Music {
@TableId(type=IdType.AUTO)
private Integer musicId;
@TableField("music_name")
private String musicName;
@TableField("music_album_name")
private String musicAlbumName;
@TableField("music_album_picUrl")
private String musicAlbumPicurl;
@TableField("music_mp3Url")
private String musicMp3url;
@TableField("music_artist_name")
private String musicArtistName;
@TableField("sheet_id")
private Integer sheetId;
}
Dao
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qf.pojo.Music;
import org.springframework.stereotype.Repository;
@Repository
public interface MusicMapper extends BaseMapper<Music> {
}
Contorller
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("music")
public class MusicController {
@Autowired
private MusicService musicService;
// Mapper CRUD 接口
// 插入一条记录
//int insert(T entity);
@RequestMapping("insert")
public String insert(Music music){
music = new Music();
//music.setMusicId(1001);
music.setMusicName("青藏高原");
musicService.insert(music);
return "success";
}
// 根据 entity 条件,删除记录
// int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
//controller层参数,无法创建,访问会报错
@RequestMapping("delete")
public String delete(QueryWrapper queryWrapper){
//封装条件
queryWrapper = new QueryWrapper<Music>();
queryWrapper.eq("music_id","46");
queryWrapper.eq("music_name","3333");
musicService.delete(queryWrapper);
return "success";
}
// // 删除(根据ID 批量删除)
// int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
@RequestMapping("deleteBatchIds")
public String deleteBatchIds(String [] ids){
musicService.deleteBatchIds(Arrays.asList(ids));
return "success";
}
// // 根据 ID 删除
// int deleteById(Serializable id);
@RequestMapping("deleteById")
public String deleteById(String id){
musicService.deleteById(id);
return "success";
}
// // 根据 columnMap 条件,删除记录
// int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
@RequestMapping("deleteByMap")
public String deleteByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("music_id","57");
map.put("music_name","青藏高原");
musicService.deleteByMap(map);
return "success";
}
// // 根据 whereEntity 条件,更新记录
// int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
@RequestMapping("update")
public String update(Music music,QueryWrapper updateWrapper){
music = new Music();
music.setMusicName("少年");
updateWrapper = new QueryWrapper<Music>();
updateWrapper.eq("music_id","56");
musicService.update(music,updateWrapper);
return "success";
}
// // 根据 ID 修改
// int updateById(@Param(Constants.ENTITY) T entity);
@RequestMapping("updateById")
public String updateById(Music music){
music = new Music();
music.setMusicId(56);
music.setMusicName("java之歌");
musicService.updateById(music);
return "success";
}
// // 根据 ID 查询
// T selectById(Serializable id);
@RequestMapping("selectById")
public Music selectById(String id){
return musicService.selectById(id);
}
// // 根据 entity 条件,查询一条记录
// T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@RequestMapping("selectOne")
public Music selectOne(QueryWrapper queryWrapper){
//封装条件
queryWrapper = new QueryWrapper<Music>();
queryWrapper.eq("music_id","1");
queryWrapper.eq("music_name","大碗宽面");
return musicService.selectOne(queryWrapper);
}
// // 查询(根据ID 批量查询)
// List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
@RequestMapping("selectBatchIds")
public List<Music> selectBatchIds(String [] ids){
return musicService.selectBatchIds(Arrays.asList(ids));
}
// // 根据 entity 条件,查询全部记录
// List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@RequestMapping("selectList")
public List<Music> selectList(QueryWrapper queryWrapper){
queryWrapper = new QueryWrapper();
queryWrapper.like("music_name","之");
return musicService.selectList(queryWrapper);
}
// // 查询(根据 columnMap 条件)
// List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
@RequestMapping("selectByMap")
public List<Music> selectByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("music_id","57");
map.put("music_name","js之歌");
return musicService.selectByMap(map);
}
// // 根据 Wrapper 条件,查询全部记录
// List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@RequestMapping("selectMaps")
public List<Map<String, Object>> selectMaps(){
QueryWrapper<Music> queryWrapper = new QueryWrapper<>();
queryWrapper = new QueryWrapper();
queryWrapper.like("music_name","之");
return musicService.selectMaps(queryWrapper);
}
// // 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
// List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@RequestMapping("selectObjs")
public List<Object> selectObjs(){
QueryWrapper<Music> queryWrapper = new QueryWrapper<>();
queryWrapper = new QueryWrapper();
queryWrapper.like("music_name","之");
return musicService.selectObjs(queryWrapper);
}
// // 根据 entity 条件,查询全部记录(并翻页)
// IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@RequestMapping("selectPage")
public IPage<Music> selectPage(){
IPage<Music> page = new Page<>(1,3);//当前页:1,每页显示条数:3
Wrapper<Music> queryWrapper = new QueryWrapper<>();
return musicService.selectPage(page,queryWrapper);
}
// // 根据 Wrapper 条件,查询全部记录(并翻页)
// IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@RequestMapping("selectMapsPage")
public IPage<Music> selectMapsPage(){
IPage<Music> page = new Page<>(1,2);//当前页:1,每页显示条数:3
QueryWrapper<Music> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("music_id","2");
return musicService.selectMapsPage(page,queryWrapper);
}
// // 根据 Wrapper 条件,查询总记录数
// Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@RequestMapping("selectCount")
public Integer selectCount(){
QueryWrapper<Music> queryWrapper = new QueryWrapper<>();
queryWrapper.ge("music_id","2");
return musicService.selectCount(queryWrapper);
}
}
Service
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface MusicService {
void insert(Music music);
void delete(QueryWrapper queryWrapper);
void deleteBatchIds(List<String> ids);
void deleteById(String id);
void deleteByMap(HashMap<String, Object> map);
void update(Music music, QueryWrapper updateWrapper);
void updateById(Music music);
Music selectById(String i);
Music selectOne(QueryWrapper queryWrapper);
List<Music> selectBatchIds(List<String> ids);
List<Music> selectList(QueryWrapper queryWrapper);
List<Music> selectByMap(HashMap<String, Object> map);
List<Map<String, Object>> selectMaps(QueryWrapper<Music> queryWrapper);
List<Object> selectObjs(QueryWrapper<Music> queryWrapper);
IPage<Music> selectPage(IPage<Music> page, Wrapper<Music> queryWrapper);
IPage<Music> selectMapsPage(IPage page, Wrapper<Music> queryWrapper);
Integer selectCount(QueryWrapper<Music> queryWrapper);
}
ServiceImpl
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MusicServiceImpl implements MusicService {
@Autowired
private MusicMapper musicMapper;
@Override
public void insert(Music music) {
musicMapper.insert(music);
}
@Override
public void delete(QueryWrapper queryWrapper) {
musicMapper.delete(queryWrapper);
}
@Override
public void deleteBatchIds(List<String> ids) {
musicMapper.deleteBatchIds(ids);
}
@Override
public void deleteById(String id) {
musicMapper.deleteById(id);
}
@Override
public void deleteByMap(HashMap<String, Object> map) {
musicMapper.deleteByMap(map);
}
@Override
public void update(Music music, QueryWrapper updateWrapper) {
musicMapper.update(music,updateWrapper);
}
@Override
public void updateById(Music music) {
musicMapper.updateById(music);
}
@Override
public Music selectById(String id) {
return musicMapper.selectById(id);
}
@Override
public Music selectOne(QueryWrapper queryWrapper) {
return musicMapper.selectOne(queryWrapper);
}
@Override
public List<Music> selectBatchIds(List<String> ids) {
return musicMapper.selectBatchIds(ids);
}
@Override
public List<Music> selectList(QueryWrapper queryWrapper) {
return musicMapper.selectList(queryWrapper);
}
@Override
public List<Music> selectByMap(HashMap<String, Object> map) {
return musicMapper.selectByMap(map);
}
@Override
public List<Map<String, Object>> selectMaps(QueryWrapper<Music> queryWrapper) {
return musicMapper.selectMaps(queryWrapper);
}
@Override
public List<Object> selectObjs(QueryWrapper<Music> queryWrapper) {
return musicMapper.selectObjs(queryWrapper);
}
@Override
public IPage<Music> selectPage(IPage<Music> page, Wrapper<Music> queryWrapper) {
return musicMapper.selectPage(page,queryWrapper);
}
@Override
public IPage<Music> selectMapsPage(IPage page, Wrapper<Music> queryWrapper) {
return musicMapper.selectMapsPage(page,queryWrapper);
}
@Override
public Integer selectCount(QueryWrapper<Music> queryWrapper) {
return musicMapper.selectCount(queryWrapper);
}
}
Mybatis-Plus使用自带分页时,需要创建该配置类
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
启动类进行测试
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.qf.dao")
public class Springboot06Application {
public static void main(String[] args) {
SpringApplication.run(Springboot06Application.class, args);
}
}
1.5代码生成器
导入依赖
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
编写配置类进行测试
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
public class MybatisPlusGenerator {
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setAuthor("yangl");
gc.setOutputDir("D:\\java2002-springboot\\springboot-06\\src\\main\\java\\com\\qf");
gc.setFileOverride(true);// 是否覆盖同名文件,默认是false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
gc.setServiceName("%sService");//去掉Service的前缀I
//gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setUrl("jdbc:mysql://localhost:3306/java2002?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
//手动指定映射表名
strategy.setInclude("tb_music");
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName("xxx");
pc.setParent("yangl");
//手动设置包名
pc.setEntity("pojo");
pc.setMapper("dao");
pc.setXml("mapper");
mpg.setPackageInfo(pc);
// 执行生成
mpg.execute();
}
}