六、代码生成器
我们知道mybatis有一个代码生成器MBG,可以生成Java实体类mapper接口和映射文件,但是MybatisPlus却更加强大,可以生成service和controller,可以配置实体类是否支持AR等,代码生成器
说明:建议数据库表名和字段名采用驼峰命名方式,和实体来一致,可以避免在对应实体类产生的性能损耗
6.1.导入依赖
<!-- Apache Velocity的依赖 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
6.2.编写配置类
@Test
public void produce(){
// 1.全局配置
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(false) // 是否开启AR模式
.setAuthor("LiRui")
.setOutputDir("E:\\workspace02\\BigShopping\\src\\main\\java")
.setFileOverride(true) // 指定文件覆盖
.setIdType(IdType.AUTO) // 设置主键自增策略
.setServiceName("%sService")// 设置生成的services接口的名字的首字母是否为I
.setBaseResultMap(true) // 基本的字段映射
.setBaseColumnList(true);// 基本的sql片段
// 2.配置数据源
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL)// 设置数据库类型
.setDriverName("com.mysql.cj.jdbc.Driver")
.setUrl("jdbc:mysql://127.0.0.1:3306/big_shopping?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8")
.setUsername("root")
.setPassword("110120");
// 3.策略配置
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true)//全局大写命名
.setDbColumnUnderline(true)// 指定表名和字段名是否使用了下划线
.setNaming(NamingStrategy.underline_to_camel)// 数据库字段下划线转驼峰命令策略
.setTablePrefix("")// 设置表前缀
.setInclude("shop_cateloge");// 设置需要生成的表
// 4.包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("com.bigshopping") // 设置父包
.setMapper("mapper")
.setService("service")
.setController("web")
.setEntity("bean");
// 5. 开始生成代码
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
ag.execute();
}
6.3.生成的service代码查看
@Service
public class DeptService extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
}
DeptService继承了ServiceImpl,在ServiceImpl中就已经注入了DeptMapper,所以,我们就不需要再次注入,在ServiceImpl中也帮我们提供了常用的CRUD方法,我们可以直接使用,
@Controller
@RequestMapping("/dept")
public class DeptController {
@Autowired
private IDeptService service;
public String select(){
service.selectList(null);
return null;
}
}