一:MyBatis-Plus简介
MyBatis-Plus是在Mybatis基础上添加了很多功能
二:在Pom.xml文件中添加依赖
com.baomidou
mybatis-plus-boot-starter
3.0.5
三:在application.properties添加配置
# 数据库配置
spring.datasource.url=jdbc:oracle:thin:@192.168.1.1:1521:orcl
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# Mybatis-Plus配置
# 指定sql映射文件位置
mybatis-plus.mapper-locations=classpath:mapper/**/*Mapper.xml
# 开户驼峰匹配
mybatis-plus.configuration.map-underscore-to-camel-case=true
# 日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
mybatis-plus.global-config.db-config.id-type=INPUT
mybatis-plus.global-config.db-config.db-type=ORACLE
# 配置扫描通用枚举,支持统配符 * 或者 ; 分割
mybatis-plus.type-enums-package=com.baomidou.springboot.entity.enums
mybatis-plus.configuration.jdbc-type-for-null=null
四:编写代码生成工具
/**
* 修改项目根路径parentPackage
* 修改mapper.xml在src/main/sources/mapper下的存放路径mapperPath
* 修改数据库配置以及tableName(要生成的表名)
* 修改项目在计算机上的根路径projectPath 便可以使用
* 其它修改看个人需求:修改完后直接运行此文件便可以了
*/
public class CodeGenerator {
public static void main(String[] args) {
//修改为项目跟路径,即application.java所在目录
String parentPackage = "com.core";
//修改为mapper.xml再src/main/sources/mapper下的存放路径
String mapperPath = "test";
//修改为需要生成的表名 //
String tableName[] = new String[] { "T_SYS_DIC"};
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
// String projectPath = System.getProperty("user.dir");
String projectPath = "D:/IDEAProject/project;
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("YingTao");
gc.setOpen(false);
gc.setFileOverride(false);// 是否覆盖同名文件,默认是false
gc.setSwagger2(true);//是否开启swagger2模式
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
/* 自定义文件命名,注意 %s 会自动填充表实体属性! */
gc.setEntityName("%sEntity");
gc.setServiceName("%sService");
//gc.setIdType(IdType.INPUT);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.ORACLE);
dsc.setUrl("jdbc:oracle:thin:@192.168.1.1:1521:orcl");
// dsc.setSchemaName("public");
dsc.setDriverName("oracle.jdbc.OracleDriver");
dsc.setUsername("username");
dsc.setPassword("password");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent(parentPackage);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/" + mapperPath
+ "/" + tableInfo.getEntityName().substring(0, tableInfo.getEntityName().length()-6) + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setCapitalMode(false);// 全局大写命名 ORACLE 注意
strategy.setTablePrefix(new String[] { "T_" });// 此处可以修改为您的表前缀
strategy.setSkipView(true);//是否跳过视图
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(false);
strategy.setRestControllerStyle(true);
// 自定义实体父类
strategy.setSuperEntityClass("com.core.base.SuperEntity");
// 自定义 mapper 父类
strategy.setSuperMapperClass("com.core.base.SuperMapper");
// 自定义 service 父类
strategy.setSuperServiceClass("com.core.base.SuperService");
// 自定义 service 实现类父类
strategy.setSuperServiceImplClass("com.core.base.SuperServiceImpl");
// 自定义 controller 父类
strategy.setSuperControllerClass("com.core.base.SuperController");
strategy.setInclude(tableName);//需要包含的表名,允许正则表达式(与exclude二选一配置)
//strategy.setExclude("");//需要排除的表名,允许正则表达式
//strategy.setSuperEntityColumns("id");//自定义基础的Entity类,公共字段
//strategy.setControllerMappingHyphenStyle(true);//驼峰转连字符
//strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// 选择 freemarker 引擎,默认 Velocity
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
五:添加通用entity父类,mapper父类,service父类,serviceImpl父类
import com.baomidou.mybatisplus.extension.activerecord.Model;
/**
* 所有实体父类
*/
@SuppressWarnings("serial")
public class SuperEntity> extends Model {
}
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 所有 mapper 父类,注意这个类不要让 mp 扫描到!!
*/
public interface SuperMapper extends BaseMapper {
// 这里可以放一些公共的方法
}
import com.baomidou.mybatisplus.extension.service.IService;
/**
* 所有服务层接口的父接口
* @param 操作所绑定的Entity
*/
public interface SuperService extends IService {
// 可以封装一下公用的接口方法
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
* 所有服务方法的父类
* @param 所操作的Mapper
* @param 所绑定的Entity
*/
public class SuperServiceImpl,T> extends ServiceImpl implements SuperService {
@Autowired
protected M superMapper;
//可以封装一些公用的方法
}
六:做配置(分页插件和oracle主键生成器)
在启动类添加Mapper接口和组件扫描:
@ComponentScan({ "com.core"})
@MapperScan({"com.core.mapper"})
/**
* @Description : mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* @Description : mybatis-plus Oracle主键生成器
*/
@Bean
public OracleKeyGenerator oracleKeyGenerator(){
return new OracleKeyGenerator();
}
七:编写
// 对应表名称
@TableName("SYS_DICT")
// 对应序列名称
@KeySequence("SEQ_DICT")
public class SysDictEntity extends SuperEntity {
private static final long serialVersionUID = 1L;
// 对应表字段
@TableField("ID")
private String id;
@TableField("TYPE_CODE")
private String typeCode;
@TableField("TYPE_NAME")
private String typeName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTypeCode() {
return typeCode;
}
public void setTypeCode(String typeCode) {
this.typeCode = typeCode;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
@Override
public String toString() {
return "SysDictEntity{" +
"id=" + id +
", typeCode=" + typeCode +
", typeName=" + typeName +
"}";
}
}
八:缩写实体类对应的Mapper接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
*BaseMapper是Plus里面已经写好的,内置了一些增删改的方法,可以直接使用
*/
public interface SysDictMapper extends SuperMapper {
// 有自己定义的查询分页方法,自定义的查询方法需要编写Mapper.xml
// 添加Page后会自动把分页信息回填进去,无需再Mapper.xml中再写
List query(Page page, @Param("map") Map paramMap);
}
dictMapper.xml文件这里忽略......(因为和Mybatis的通用写法一样.没有改变)
九:配置service接口和实现类
import com.baomidou.mybatisplus.extension.service.IService;
/**
* IService是Plus内置的,里面有很多通用的方法.增删改查等
*/
public interface SysDictService extends SuperService {
//添加自定义的方法
Page getValueList(Page page,String typeCode);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* 服务实现类
*
*/
@Service
public class SysDictServiceImpl extends SuperServiceImpl implements SysDictService {
@Autowired
private SysDictMapper sysDictMapper;
@Override
public Page getValueList(Page page,String typeCode) {
page= sysDictMapper.getValueList(page,typeCode);
return page;
}
}
十:在Controller中的举例用法
@RestController
@RequestMapping("/sysDict")
public class SysDictController extends SuperController {
@Autowired
private SysDictService sysDictService;
/**
* @Title: query
* @Description: 分页查询
*/
@RequestMapping(value = "/queryByTypeCode", method = RequestMethod.GET)
public IPage query(String typeCode){
// new Page分页信息(起始点,条数)
return sysDictService.getValueList(new Page(0, 10),typeCode);
}
/**
* @Title: query
* @Description: 新增一条信息
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void add(SysMenuEntity entity) {
// ActiveRecord模式,用实体类继承Model后就可以使用
// entity.insert();
// 或者用service里面的内置的方法
return sysMenuService.insert(entity);
}
}