日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot 配置 generator代码生成+knife4j接口文档(2种模板设置、逻辑删除、字段填充 含代码粘贴可用)保姆级教程(注意事项+建表SQL+代码生成类封装+测试类)

發布時間:2024/10/6 javascript 45 豆豆

保姆級教程,邏輯刪除及字段自動填充設置,特別要說明的是本次用的是MySQL數據庫,如果使用Oracle數據庫是,數據庫配置需要改變,數據庫表一定要大寫,否則無法生成代碼。

數據庫表

CREATE TABLE `student` (`id` int(64) NOT NULL AUTO_INCREMENT COMMENT '編號',`name` varchar(32) DEFAULT NULL COMMENT '姓名',`age` int(3) DEFAULT NULL COMMENT '年齡',`is_delete` int(1) NOT NULL DEFAULT '0' COMMENT '是否刪除',`create_time` datetime DEFAULT NULL COMMENT '入庫時間',`update_time` datetime DEFAULT NULL COMMENT '修改時間',PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

1.依賴

代碼生成工具使用 mybatis-plus-generator,generator默認使用的模板為 velocity-engine-core,也可以使用freemarker(需要額外設置)。接口文檔使用 knife4j-spring-boot-starter。

<!--代碼生成插件--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.1.tmp</version></dependency><!--代碼生成模板--><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.2</version></dependency><!--可選代碼生成模板--><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.29</version></dependency><!--接口文檔--><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.2</version></dependency><!--strategy.setEntityLombokModel(true);如果設置為true是需要lombok的--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>

yml配置

mybatis-plus:mapper-locations: classpath*:/com/example/demo/**/mapper/xml/*.xmlglobal-config:db-config:logic-not-delete-value: 0logic-delete-value: 1

2.代碼生成類

如果要使用freemarker模板,需要額外配置 .setTemplateEngine(new FreemarkerTemplateEngine()); 啟用 .setSwagger2(true);

class CodeGenerator {/*** 項目根路徑*/private static final String PROJECT_PATH = "E:\yuanzheng-codebase\m-framework\codegenerator";/*** 注釋@auth 名稱*/private static final String AUTH = "auth";/*** 父包全限定類名*/private static final String PARENT = "com.example.demo";/*** 模塊名稱*/private static final String MODEL_NAME = "student";/*** 忽略的表前綴*/private static final String[] IGNORE_TABLE_PFX = new String[]{"table_", "t_"};/*** 要生成的表名*/private static final String TABLE_NAMES = "student";/*** 數據源配置*/private static final DataSourceConfig DSC = new DataSourceConfig();static {DSC.setDbType(DbType.MYSQL);DSC.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true");DSC.setDriverName("com.mysql.cj.jdbc.Driver");DSC.setUsername("root");DSC.setPassword("root");}@Testvoid test() {main(null);}static void main(String[] args) {// 代碼生成器AutoGenerator mpg = new AutoGenerator();/** 全局配置*/GlobalConfig gc = new GlobalConfig();// 輸出路徑gc.setOutputDir(PROJECT_PATH + "/src/main/java");// 設置作者gc.setAuthor(AUTH);// 生成代碼后,是否打開文件夾gc.setOpen(false);// 是否覆蓋原來代碼gc.setFileOverride(false);// 去掉service的I前綴,一般只需要設置service就行 // gc.setServiceName("%sService"); // gc.setMapperName("%sMapper"); // gc.setXmlName("%sMapper"); // gc.setServiceImplName("%sServiceImpl"); // gc.setControllerName("%sController");// 日期格式gc.setDateType(DateType.ONLY_DATE);// 實體屬性 Swagger2 注解,實體類上會增加注釋gc.setSwagger2(true);mpg.setGlobalConfig(gc);/** 數據源配置*/mpg.setDataSource(DSC);/** 配置模板(generator默認的是velocity,使用freemarker的話要打開此項設置)*/// mpg.setTemplateEngine(new FreemarkerTemplateEngine());/** 包配置*/PackageConfig pc = new PackageConfig();pc.setParent(PARENT);pc.setModuleName(MODEL_NAME);pc.setEntity("entity");pc.setMapper("mapper");pc.setService("service");pc.setController("controller");mpg.setPackageInfo(pc);/** 策略配置*/StrategyConfig strategy = new StrategyConfig();strategy.setInclude(TABLE_NAMES);strategy.setTablePrefix(IGNORE_TABLE_PFX);// 包的命名規則,使用駝峰規則strategy.setNaming(NamingStrategy.underline_to_camel);// 列的名稱,使用駝峰規則strategy.setColumnNaming(NamingStrategy.underline_to_camel);// 是否使用lombok(要確認項目是否有lombok)strategy.setEntityLombokModel(true);// 是否使用strategy.setRestControllerStyle(true);// 邏輯刪除(要結合數據表字段使用)strategy.setLogicDeleteFieldName("is_delete");// 自動填充字段TableFill fillInsert = new TableFill("create_time", FieldFill.INSERT);TableFill fillUpdate = new TableFill("update_time", FieldFill.UPDATE);List fillLists = new ArrayList();fillLists.add(fillInsert);fillLists.add(fillUpdate);strategy.setTableFillList(fillLists);//樂觀鎖//strategy.setVersionFieldName("version");mpg.setStrategy(strategy);// 執行mpg.execute();} }

3.生成后的結構

Student
可以看到代碼生成設置的邏輯刪除字段、INSERT和UPDATE填充字段的注釋。

@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value="Student對象", description="") public class Student implements Serializable {private static final long serialVersionUID=1L;@ApiModelProperty(value = "編號")@TableId(value = "id", type = IdType.AUTO)private Integer id;@ApiModelProperty(value = "姓名")private String name;@ApiModelProperty(value = "年齡")private Integer age;@ApiModelProperty(value = "是否刪除")@TableLogicprivate Integer isDelete;@ApiModelProperty(value = "入庫時間")@TableField(fill = FieldFill.INSERT)private Date createTime;@ApiModelProperty(value = "修改時間")@TableField(fill = FieldFill.UPDATE)private Date updateTime; }

DateObjectHandler
處理一下填充字段。

@Component public class DateObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime", new Date(), metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", new Date(), metaObject);} }

Controller
簡單測試一下。

@RestController @RequestMapping("/student") @Api(value = "學生", tags = {"增刪改查"}) public class StudentController {@Autowiredprivate IStudentService studentService;@GetMapping("/get")@ApiOperation(value = "獲取學生列表")public List<Student> getStudents() {LambdaQueryWrapper<Student> query = Wrappers.lambdaQuery(Student.class);return studentService.list(query);}@PostMapping("/add")@ApiOperation(value = "新增學生信息")public boolean addStudent(@ApiParam Student student) {return studentService.save(student);}@PostMapping("/update")@ApiOperation(value = "修改學生信息")public boolean updateStudent(@ApiParam Student student) {return studentService.updateById(student);}@GetMapping("/del")@ApiOperation(value = "刪除學生信息")public boolean deleteStudent(@ApiParam(name = "id",value = "唯一ID") Integer id) {return studentService.removeById(id);} }

4.使用 http://ip:port/doc.html

新增一條數據后,creatTime字段自動填充了;


修改后,updateTime字段也自動填充了;


刪除后,查詢列表已經沒有數據了;


查詢數據庫,可以看到數據是邏輯刪除了。

總結

以上是生活随笔為你收集整理的SpringBoot 配置 generator代码生成+knife4j接口文档(2种模板设置、逻辑删除、字段填充 含代码粘贴可用)保姆级教程(注意事项+建表SQL+代码生成类封装+测试类)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。