一、新建项目
    1、构建项目
    image.png

    2、导入依赖pom.xml介绍

    1. <parent>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-parent</artifactId>
    4. <version>2.5.10</version>
    5. <relativePath/> <!-- lookup parent from repository -->
    6. </parent>
    7. <dependency>
    8. <groupId>org.springframework.boot</groupId>
    9. <artifactId>spring-boot-starter-web</artifactId>
    10. </dependency>
    11. <dependency>
    12. <groupId>org.projectlombok</groupId>
    13. <artifactId>lombok</artifactId>
    14. <optional>true</optional>
    15. </dependency>
    16. <dependency>
    17. <groupId>org.springframework.boot</groupId>
    18. <artifactId>spring-boot-starter-test</artifactId>
    19. <scope>test</scope>
    20. </dependency>
    21. <dependency>
    22. <groupId>commons-lang</groupId>
    23. <artifactId>commons-lang</artifactId>
    24. <version>2.6</version>
    25. </dependency>
    26. <plugin>
    27. <groupId>org.springframework.boot</groupId>
    28. <artifactId>spring-boot-maven-plugin</artifactId>
    29. <version>2.5.10</version>
    30. <configuration>
    31. <excludes>
    32. <exclude>
    33. <groupId>org.projectlombok</groupId>
    34. <artifactId>lombok</artifactId>
    35. </exclude>
    36. </excludes>
    37. </configuration>
    38. </plugin>

    3、新建目录

    image.png

    二、mybatisplus整合
    1、导入依赖

    1. <dependency>
    2. <groupId>com.baomidou</groupId>
    3. <artifactId>mybatis-plus-boot-starter</artifactId>
    4. <version>3.3.2</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>mysql</groupId>
    8. <artifactId>mysql-connector-java</artifactId>
    9. <scope>runtime</scope>
    10. </dependency>

    2、配置application.properties文件

    1. mybatis-plus:
    2. configuration:
    3. map-underscore-to-camel-case: true
    4. auto-mapping-behavior: full
    5. mapper-locations: classpath:mapper/*.xml
    6. spring:
    7. datasource:
    8. driver-class-name: com.mysql.jdbc.Driver
    9. url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
    10. username: root
    11. password: root
    12. logging:
    13. level:
    14. com.qf.firstspringboot.mapper: DEBUG

    3、编写实体

    1. @Data
    2. @TableName("t_users") //驼峰名
    3. public class User implements Serializable {
    4. @TableId(value = "id",type = IdType.AUTO)
    5. private Integer id;
    6. private String name;
    7. private String password;
    8. private String sex;
    9. private Date birthday;
    10. @TableField("registTime")
    11. private Date registTime;
    12. }

    4、编写Mapper

    1. @Mapper
    2. public interface IUserDao extends BaseMapper<User> {
    3. }

    5、编写service

    1. public interface IUserService {
    2. public Integer insert(User user);
    3. public Integer update(User user);
    4. public Integer delete(Integer id);
    5. public IPage findBypage(Integer pageNum, Integer pageSize, User user);
    6. public User findById(Integer id);
    7. }
    1. @Service
    2. public class UserService implements IUserService {
    3. @Autowired
    4. private IUserDao iUserDao;
    5. @Override
    6. public Integer insert(User user) {
    7. int insert = iUserDao.insert(user);
    8. return insert;
    9. }
    10. @Override
    11. public Integer update(User user) {
    12. int update = iUserDao.updateById(user);
    13. return update;
    14. }
    15. @Override
    16. public Integer delete(Integer id) {
    17. int i = iUserDao.deleteById(id);
    18. return i ;
    19. }
    20. @Override
    21. public IPage findBypage(Integer pageNum, Integer pageSize, User user) {
    22. Page page = new Page(pageNum,pageSize);
    23. QueryWrapper wrapper = new QueryWrapper<User>();
    24. wrapper.eq(StringUtils.isNotBlank(user.getName()),"name",user.getName());
    25. IPage iPage = iUserDao.selectPage(page, wrapper);
    26. return iPage;
    27. }
    28. @Override
    29. public User findById(Integer id) {
    30. User user = iUserDao.selectById(id);
    31. return user;
    32. }

    6、分页插件

    1. @Configuration
    2. public class MybatisPlusConfig {
    3. @Bean //就相当于bean
    4. public PaginationInterceptor paginationInterceptor() {
    5. return new PaginationInterceptor();
    6. }
    7. }

    mybatis-plus 自动代码生成器

    1. <!-- mybatis-plus依赖 -->
    2. <dependency>
    3. <groupId>com.baomidou</groupId>
    4. <artifactId>mybatis-plus-boot-starter</artifactId>
    5. <version>3.3.2</version>
    6. </dependency>
    7. <!-- mysql驱动包 -->
    8. <dependency>
    9. <groupId>mysql</groupId>
    10. <artifactId>mysql-connector-java</artifactId>
    11. </dependency>
    12. <!-- 测试包 -->
    13. <dependency>
    14. <groupId>org.springframework.boot</groupId>
    15. <artifactId>spring-boot-starter-test</artifactId>
    16. </dependency>
    17. <!-- 代码生成器 -->
    18. <dependency>
    19. <groupId>com.baomidou</groupId>
    20. <artifactId>mybatis-plus-generator</artifactId>
    21. <version>3.3.2</version>
    22. </dependency>
    23. <dependency>
    24. <groupId>org.freemarker</groupId>
    25. <artifactId>freemarker</artifactId>
    26. <version>2.3.30</version>
    27. </dependency>

    编写代码

    1. package com.qf.util;
    2. import com.baomidou.mybatisplus.core.toolkit.StringPool;
    3. import com.baomidou.mybatisplus.generator.AutoGenerator;
    4. import com.baomidou.mybatisplus.generator.InjectionConfig;
    5. import com.baomidou.mybatisplus.generator.config.*;
    6. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    7. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    8. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    9. import java.util.ArrayList;
    10. import java.util.HashMap;
    11. import java.util.List;
    12. import java.util.Map;
    13. public class CodeGenerator {
    14. // 固定
    15. private static final String projectPath = System.getProperty("user.dir");
    16. private static final String outPutDir = projectPath + "/src/main/java";
    17. // 自定义
    18. private static final String author = "hzp";
    19. private static final String packageName = "test";
    20. private static final String moduleName = "door";
    21. private static final String[] tableName = ("user_entity").split(",");
    22. private static final String tablePrefix = "sys";
    23. public static void main(String[] args) {
    24. // 代码生成器
    25. AutoGenerator mpg = new AutoGenerator();
    26. // 设置全局配置
    27. mpg.setGlobalConfig(getGlobalConfig());
    28. // 设置数据源配置
    29. mpg.setDataSource(getDataSourceConfig());
    30. // 包配置
    31. PackageConfig pc = getPackageConfig();
    32. mpg.setPackageInfo(pc);
    33. // 自定义配置
    34. mpg.setCfg(getInjectionConfig());
    35. // 配置模板
    36. TemplateConfig templateConfig = new TemplateConfig();
    37. templateConfig.setXml(null);
    38. mpg.setTemplate(templateConfig);
    39. // 策略配置
    40. mpg.setStrategy(getStrategyConfig());
    41. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    42. mpg.execute();
    43. }
    44. private static GlobalConfig getGlobalConfig() {
    45. // 全局配置
    46. GlobalConfig gc = new GlobalConfig();
    47. gc.setOutputDir(outPutDir);
    48. gc.setAuthor(author);
    49. gc.setOpen(false);
    50. gc.setEntityName("%sEntity");
    51. gc.setMapperName("%sDao");
    52. gc.setServiceName("%sService");
    53. // 是否覆盖文件,默认false不覆盖
    54. gc.setFileOverride(true);
    55. // XML ResultMap
    56. gc.setBaseResultMap(true);
    57. // XML columList
    58. gc.setBaseColumnList(true);
    59. // gc.setSwagger2(true); 实体属性 Swagger2 注解
    60. return gc;
    61. }
    62. private static DataSourceConfig getDataSourceConfig() {
    63. // 数据源配置
    64. DataSourceConfig dsc = new DataSourceConfig();
    65. dsc.setUrl("jdbc:mysql://localhost:3306/mybatis01?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false");
    66. // dsc.setSchemaName("public");
    67. // String driverName = "com.mysql.jdbc.Driver";
    68. String driverName = "com.mysql.jdbc.Driver";
    69. dsc.setDriverName(driverName);
    70. dsc.setUsername("root");
    71. dsc.setPassword("");
    72. return dsc;
    73. }
    74. private static PackageConfig getPackageConfig() {
    75. // 包配置
    76. PackageConfig pc = new PackageConfig();
    77. // 包名称
    78. pc.setParent(packageName);
    79. // 模块名称
    80. pc.setModuleName(moduleName);
    81. return pc;
    82. }
    83. private static InjectionConfig getInjectionConfig() {
    84. // 自定义配置
    85. InjectionConfig cfg = new InjectionConfig() {
    86. @Override
    87. public void initMap() {
    88. }
    89. };
    90. // 如果模板引擎是 freemarker
    91. String templatePath = "/templates/mapper.xml.ftl";
    92. List<FileOutConfig> focList = new ArrayList<>();
    93. focList.add(new FileOutConfig(templatePath) {
    94. @Override
    95. public String outputFile(TableInfo tableInfo) {
    96. return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName().replace("Entity", "")
    97. + "Mapper" + StringPool.DOT_XML;
    98. }
    99. });
    100. cfg.setFileOutConfigList(focList);
    101. return cfg;
    102. }
    103. private static StrategyConfig getStrategyConfig() {
    104. // 策略配置
    105. StrategyConfig strategy = new StrategyConfig();
    106. strategy.setNaming(NamingStrategy.underline_to_camel);
    107. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    108. // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
    109. strategy.setEntityLombokModel(true);
    110. strategy.setRestControllerStyle(true);
    111. // 公共父类
    112. // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
    113. // 写于父类中的公共字段
    114. // strategy.setSuperEntityColumns("id");
    115. // strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
    116. strategy.setInclude(tableName);
    117. strategy.setControllerMappingHyphenStyle(true);
    118. strategy.setTablePrefix(tablePrefix + "_");
    119. return strategy;
    120. }
    121. }

    三、整合JPA
    1、导入依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-data-jpa</artifactId>
    4. </dependency>
    5. <dependency>
    6. <groupId>com.alibaba</groupId>
    7. <artifactId>fastjson</artifactId>
    8. <version>1.2.75</version>
    9. </dependency>

    2、配置YML文件

    1. jpa:
    2. hibernate:
    3. ddl-auto: update #create-drop/create/update/none
    4. show-sql: true #打印sql语句

    3、编写实体

    1. @Data
    2. @Entity(name = "t_user")
    3. public class UserEntity implements Serializable {
    4. @Id
    5. @GenericGenerator(name = "idGenerator", strategy = "uuid") //这个是hibernate的注�?生成32位UUID
    6. @GeneratedValue(generator = "idGenerator")
    7. private String id;
    8. @Column
    9. private String username;
    10. @Column
    11. private String password;
    12. @Column
    13. private String company;
    14. @Column
    15. private String files;
    16. @Column
    17. private String companyPerson;
    18. @Column
    19. private String card;
    20. @Column
    21. private String orgCard;
    22. @Column
    23. private String email;
    24. @Column
    25. private BigDecimal money;
    26. @Column
    27. private String roleId;
    28. @Column
    29. private String status = ConstentUtil.STATUS_ON;
    30. @Column
    31. private String creater;
    32. @Column
    33. private String updater;
    34. @Column
    35. private Date createTime;
    36. @Column
    37. private Date updateTime;
    38. }

    4、编写dao

    1. @Repository
    2. public interface UserJpaDao extends JpaRepository<UserEntity,String>,
    3. JpaSpecificationExecutor<UserEntity> {
    4. UserEntity findByUsernameAndPassword(String username,String password);
    5. }

    5、编写service

    1. public interface IUserService {
    2. UserEntity login(String username,String password) throws Exception;
    3. Boolean insert(UserEntity userEntity) throws Exception;
    4. Boolean update(UserEntity userEntity) throws Exception;
    5. Boolean delete(String id) throws Exception;
    6. UserEntity findByOne(String id) throws Exception;
    7. List<UserEntity> findAll(UserEntity userEntity, Integer pageNum, Integer pageSize) throws Exception;
    8. }
    1. @Service
    2. public class UserServiceImpl implements IUserService {
    3. @Autowired
    4. private UserJpaDao userJpaDao;
    5. @Override
    6. public UserEntity login(String username, String password) throws Exception {
    7. String token = null;
    8. UserEntity userEntity = new UserEntity();
    9. userEntity.setUsername(username);
    10. userEntity.setPassword(password);
    11. if(vaild(userEntity)){
    12. userEntity = userJpaDao.findByUsernameAndPassword(username, password);
    13. }
    14. return userEntity;
    15. }
    16. @Override
    17. public Boolean insert(UserEntity userEntity) throws Exception {
    18. return null;
    19. }
    20. @Override
    21. public Boolean update(UserEntity userEntity) throws Exception {
    22. return null;
    23. }
    24. @Override
    25. public Boolean delete(String id) throws Exception {
    26. return null;
    27. }
    28. @Override
    29. public UserEntity findByOne(String id) throws Exception {
    30. return null;
    31. }
    32. @Override
    33. public List<UserEntity> findAll(UserEntity userEntity, Integer pageNum, Integer pageSize) throws Exception {
    34. return null;
    35. }
    36. private Boolean vaild(UserEntity userEntity) throws Exception{
    37. Boolean isBool =false;
    38. if(null == userEntity){
    39. throw new RuntimeException("用户信息不能为空!!");
    40. }
    41. if(StringUtils.isBlank(userEntity.getUsername())){
    42. throw new RuntimeException("用户名不能为空!!");
    43. }
    44. if(StringUtils.isBlank(userEntity.getPassword())){
    45. throw new RuntimeException("密码不能为空!!");
    46. }
    47. isBool = true;
    48. return isBool;
    49. }
    50. }

    四、swagger-ui整合
    1、导入依赖包

    1. <dependency>
    2. <groupId>io.springfox</groupId>
    3. <artifactId>springfox-swagger2</artifactId>
    4. <version>2.8.0</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>io.springfox</groupId>
    8. <artifactId>springfox-swagger-ui</artifactId>
    9. <version>2.8.0</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>com.github.xiaoymin</groupId>
    13. <artifactId>swagger-bootstrap-ui</artifactId>
    14. <version>1.8.5</version>
    15. </dependency>

    2、配置对象

    1. @Bean
    2. public Docket createRestApi() {
    3. //http://ip地址:端口/项目名/swagger-ui.html#/
    4. ApiInfo apiInfo = new ApiInfoBuilder()
    5. .title("互联网医院") //网站标题
    6. .description("互联网医院API") //网站描述
    7. .version("9.0") //版本
    8. .contact(new Contact("qf","1000phone","1")) //联系人
    9. .license("tcp") //协议
    10. .licenseUrl("http://localhost:8014/") //协议url
    11. .build();
    12. return new Docket(DocumentationType.SWAGGER_2) //swagger版本
    13. .pathMapping("/")
    14. .select()
    15. //扫描那些controller
    16. .apis(RequestHandlerSelectors.basePackage("com.qf.controller"))
    17. .paths(PathSelectors.any())
    18. .build()
    19. .apiInfo(apiInfo);
    20. }

    五、统一异常处理
    1、导入依赖包

    1. <dependency>
    2. <groupId>com.alibaba</groupId>
    3. <artifactId>fastjson</artifactId>
    4. <version>1.2.75</version>
    5. </dependency>

    2、编写异常处理类

    1. @ControllerAdvice
    2. @ResponseBody
    3. public class GlobalExceptions {
    4. @ExceptionHandler
    5. public String otherException(Exception e){
    6. return Result.fail(500,"服务器异常!",e.getMessage());
    7. }
    8. }

    3、编写异常处理对象

    1. @Data
    2. public class ResultUtil implements Serializable {
    3. private Integer code;
    4. private String msg;
    5. private Object data;
    6. }

    4、编写异常工具类

    1. public class Result {
    2. public static String success(Integer code,String msg,Object data){
    3. ResultUtil resultUtil = new ResultUtil();
    4. resultUtil.setCode(code);
    5. resultUtil.setMsg(msg);
    6. resultUtil.setData(data);
    7. return JSON.toJSONString(resultUtil);
    8. }
    9. public static String fail(Integer code, String msg, String error){
    10. ResultUtil resultUtil = new ResultUtil();
    11. resultUtil.setCode(code);
    12. resultUtil.setMsg(msg);
    13. resultUtil.setData(error);
    14. return JSON.toJSONString(resultUtil);
    15. }
    16. }

    六、定时任务
    1、添加注解

    1. @EnableScheduling

    2、编写定时任务

    1. @Scheduled(cron="0/5 * * * * ?")
    2. public void executeFileDownLoadTask() {
    3. System.out.println("定时任务启动");
    4. }

    cron表达式从左到右(用空格隔开):秒 分 小时 日期 月份 星期 年份
    0 0 10,14,16 ? 每天上午10点,下午2点,4点每天上午10点,下午2点,4点
    0 0/30 9-17 ? 朝九晚五工作时间内每半小时
    0 0 12 ? WED 表示每个星期三中午12点
    0 0 12
    ? 每天中午12点触发
    0 15 10 ?
    每天上午10:15触发
    0 15 10
    ? 每天上午10:15触发
    0 15 10
    ? 每天上午10:15触发
    0 15 10 ? 2019 2019年的每天上午10:15触发
    0 14 ? 在每天下午2点到下午2:59期间的每1分钟触发
    0 0/5 14
    ? 在每天下午2点到下午2:55期间的每5分钟触发
    0 0/5 14,18
    ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
    0 0-5 14
    ? 在每天下午2点到下午2:05期间的每1分钟触发
    0 10,44 14 ? 3 WED 每年三月的星期三的下午2:10和2:44触发
    0 15 10 ?
    MON-FRI 周一至周五的上午10:15触发
    0 15 10 15 ? 每月15日上午10:15触发
    0 15 10 L
    ? 每月最后一日的上午10:15触发
    0 15 10 ? 6L 每月的最后一个星期五上午10:15触发
    0 15 10 ?
    6L 2018-2019 2018年至2019年的每月的最后一个星期五上午10:15触发
    0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发