15个实用的代码生成模板,CRUD与配置
15个实用的代码生成模板CRUD与配置# 15个实用的代码生成模板CRUD与配置全搞定在项目开发中重复编写相似的CRUD代码和配置文件不仅耗时耗力还容易出错。作为一名Java开发工程师我收集整理了15个实用的代码生成模板能够极大提升开发效率特别适合各种项目快速开发场景。## 一、基础CRUD模板1. **MyBatis-Plus通用Mapper**javapublic interface BaseMapper {InsertProvider(type BaseSqlProvider.class, method “insert”)int insert(T entity);DeleteProvider(type BaseSqlProvider.class, method “deleteById”)int deleteById(Param(“id”) Long id);UpdateProvider(type BaseSqlProvider.class, method “update”)int update(T entity);SelectProvider(type BaseSqlProvider.class, method “selectById”)T selectById(Param(“id”) Long id);SelectProvider(type BaseSqlProvider.class, method “selectAll”)List selectAll();}2. **Spring Boot Controller模板**javaRestControllerRequestMapping(“/api/{entityName}”)public class GenericController {Autowiredprivate GenericService service;PostMappingpublic ResponseEntity? create(RequestBody T entity) {service.save(entity);return ResponseEntity.ok().build();}// 其他标准CRUD方法...}## 二、高级查询模板3. **分页查询模板**javapublic PageResult queryByPage(PageQuery query) {IPage page new Page(query.getPage(), query.getSize());LambdaQueryWrapper wrapper new LambdaQueryWrapper();// 动态构建查询条件...return PageResult.of(baseMapper.selectPage(page, wrapper));}4. **动态条件查询**javapublic List queryByExample(Example example) {QWrapper wrapper QWrapper.query();if (example.getId() ! null) {wrapper.eq(“id”, example.getId());}// 其他条件...return mapper.selectList(wrapper);}## 三、配置类模板5. **Swagger配置**javaConfigurationEnableSwagger2public class SwaggerConfig {Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(“com.example”)).paths(PathSelectors.any()).build();}}6. **Redis配置模板**javaConfigurationEnableCachingpublic class RedisConfig extends CachingConfigurerSupport {Beanpublic RedisTemplateString, Object redisTemplate(RedisConnectionFactory factory) {RedisTemplateString, Object template new RedisTemplate();template.setConnectionFactory(factory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));return template;}}## 四、日志与异常处理模板7. **全局异常处理**javaRestControllerAdvicepublic class GlobalExceptionHandler {ExceptionHandler(Exception.class)public ResponseEntity handleException(Exception ex) {ErrorResponse error new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(),ex.getMessage());return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);}}8. **日志AOP切面**javaAspectComponentSlf4jpublic class LogAspect {Around(“annotation(com.example.annotation.Log)”)public Object around(ProceedingJoinPoint point) throws Throwable {long startTime System.currentTimeMillis();Object result point.proceed();log.info(“方法 {} 执行耗时: {}ms”,point.getSignature(), System.currentTimeMillis()-startTime);return result;}}## 五、实用工具模板9. **ID生成器**javapublic class IdGenerator {private static final Snowflake snowflake new Snowflake(1, 1);public static long nextId() {return snowflake.nextId();}}10. **Excel导出工具**javapublic class ExcelExporter {public static void export(List data, Class clazz, OutputStream out) {ExcelWriter writer EasyExcel.write(out).build();WriteSheet sheet EasyExcel.writerSheet().build();writer.write(data, sheet);writer.finish();}}## 六、微服务相关模板11. **Feign客户端配置**javaFeignClient(name “user-service”,configuration FeignConfig.class,fallback UserClientFallback.class)public interface UserClient {GetMapping(“/users/{id}”)User getById(PathVariable Long id);}12. **Spring Cloud Gateway路由**ymlspring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path/api/users/**## 七、安全认证模板13. **JWT工具类**javapublic class JwtUtils {public static String generateToken(UserDetails userDetails) {return Jwts.builder().setSubject(userDetails.getUsername()).setExpiration(new Date(System.currentTimeMillis() 3600000)).signWith(SignatureAlgorithm.HS512, “secret”).compact();}// 其他JWT方法...}14. **Spring Security配置**javaConfigurationEnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throw