自动生成
public class MPGenerator {
public static void main(String[] args) {
AutoGenerator autoGenerator = new AutoGenerator();
//数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setUrl("jdbc:mysql://...");
dataSourceConfig.setUsername("...");
dataSourceConfig.setPassword("...");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
autoGenerator.setDataSource(dataSourceConfig);
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java"); // 输出的根目录
globalConfig.setOpen(false); // 生成后是否打开文件资源管理器
globalConfig.setAuthor("...");
globalConfig.setServiceName("%sService"); // 设置service接口名前没有‘I’
autoGenerator.setGlobalConfig(globalConfig);
//包信息
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.example"); // 父包目录
packageConfig.setController("controller");
packageConfig.setService("service");
packageConfig.setServiceImpl("service.impl");
packageConfig.setMapper("com.example/mapper/xml");
packageConfig.setEntity("entity");
autoGenerator.setPackageInfo(packageConfig);
//配置策略
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setEntityLombokModel(true);
strategyConfig.setNaming(NamingStrategy.underline_to_camel); // 将数据库中的字段的下划线转为驼峰命名
autoGenerator.setStrategy(strategyConfig);
autoGenerator.execute();
}
}
Mapper.xml 不生效
报错:
Invalid bound statement (not found):...
官网解决方案:
https://baomidou.com/guide/faq.html
注意,生成的Mapper.xml放在src下,如用IDEA是不会扫描此文件夹下的xml文件:
-
在pom.xml的build下加入:
<build>
<resources>
<resource>
<!-- xml放在java目录下-->
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build> -
在springboot配置文件下配置,classpath是相对于target下的classes目录:
mybatis-plus.mapper-locations=classpath:/.../mapper/xml/*.xml