编程随笔 编程随笔
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)

liyao52033

走运时,要想到倒霉,不要得意得过了头;倒霉时,要想到走运,不必垂头丧气。心态始终保持平衡,情绪始终保持稳定,此亦长寿之道
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)
  • springboot

    • MyBatis Plus使用
    • springboot2引入swagger3
    • EasyCaptcha验证码存入redis的使用
    • 常用方法
      • 1.查询数据是否存在
      • 2. yml文件常用配置
      • 3.MapStruct代码映射工具
      • 4. validator注解的使用
    • Elasticsearch全文搜索
    • canal同步mysql数据到es中
    • SpringSecurity使用
    • StringUtils 工具类使用
    • HTTP各种参数发送
    • EasyExcel之Excel导入导出
    • EasyExcel具体使用
    • FreeMarker 模板引擎入门
    • FreeMarker生成文件及WEB使用
    • TrueLicense 创建及安装证书
  • 服务器相关

  • 腾讯云cos对象操作

  • 后端
  • springboot
华总
2023-08-24
0
0
目录

常用方法原创

# 1.查询数据是否存在

//导入依赖
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>3.0.5</version>
</dependency>

 // 创建类
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
    // CrudRepository内置boolean existsById(ID id),这个方法将会返回一个布尔值,表示该ID是否存在。
}

//调用
 @GetMapping("/delete")
    public Result<String> deleteById(String id){
        boolean existsById = postEsDao.existsById(id);
        if (!existsById) {
            return Result.failure(ErrorCode.NOT_FOUND_ERROR);
        }
        postEsDao.deleteById(id);
        return Result.success("删除成功");
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 2. yml文件常用配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatisdemo
    username: root
    password: Hik@1234
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher // 使用ant_path_matcher策略来匹配请求的URL路径
    validation:
      enabled: true
  application:
    name: spring-boot
  profiles:
    active: dev
  jackson:
    default-property-inclusion: non_null //返回消息为null则不显示
    date-format: yyyy-MM-dd HH:mm:ss  // 全局格式化时间
  elasticsearch:
    uris: http://localhost:9200
    username: root
    password: 123456

mybatis-plus:
  configuration:
    call-setters-on-nulls: true // 如果数据库字段的值为NULL,将NULL作为参数传递给setter方法,避免了空指针异常。
    map-underscore-to-camel-case: false
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    sql-parser-cache: true
  global-config:
    db-config:
      logic-delete-field: isDelete
      logic-delete-value: 1
      logic-not-delete-value: 0
      column-format: ''
          
knife4j:
  enable: true
  setting:
    language: zh_cn

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# 3.MapStruct代码映射工具

它简化了Java Bean之间映射的过程。它在编译时生成映射代码,从而消除了开发人员手动编写重复且容易出错的映射代码的需要。

MapStruct使用简单直观的基于注释的方法来配置和自定义映射过程。它支持各种映射策略,例如字段映射、方法映射、构造函数映射等。它还允许开发人员使用表达式语言编写自定义映射逻辑,提供了在复杂映射场景中的灵活性。

使用MapStruct的一个优点是,它生成高度优化和高效的映射代码,从而提高了性能并减少了内存使用。它还支持与Spring和其他框架的集成。

假设我们有两个Java Bean,分别是Student和StudentDTO,它们的字段如下所示:

//导入依赖
<dependency>
  <groupId>org.mapstruct</groupId>
  <artifactId>mapstruct</artifactId>
  <version>1.5.5.Final</version>
</dependency>
<dependency>
  <groupId>org.mapstruct</groupId>
  <artifactId>mapstruct-processor</artifactId>
  <version>1.5.5.Final</version>
</dependency>

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.11.0</version>
    <configuration>
      <source>19</source>
      <target>19</target>
      <annotationProcessorPaths>
        <path>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>${lombok.version}</version>
        </path>
        <path>
          <groupId>org.mapstruct</groupId>
          <artifactId>mapstruct-processor</artifactId>
          <version>${org.mapstruct.version}</version>
        </path>
      </annotationProcessorPaths>
    </configuration>
 </plugin>
    
public class Student {
    private String name;
    private int age;
    private String address;

    // getters and setters
}

public class StudentDTO {
    private String name;
    private int age;

    // getters and setters
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

我们想要将一个Student对象映射到一个StudentDTO对象。使用MapStruct,我们可以定义一个映射接口,如下所示:

@Mapper
public interface StudentMapper {
    StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);

    @Mapping(source = "address", target = "ignoredField")
    StudentDTO studentToStudentDTO(Student student);
    // List<StudentDTO> studentToStudentDTO(List<Student> student)
}

接口定义完成后maven install自动生成接口实现类
1
2
3
4
5
6
7
8
9
10

在这个示例中,我们使用了@Mapper注解来告诉MapStruct这是一个映射接口。我们还定义了一个静态的INSTANCE字段,它使用了Mappers.getMapper()方法来获取一个映射器实例。

接下来,我们定义了一个studentToStudentDTO()方法,它将一个Student对象映射到一个StudentDTO对象。我们使用了@Mapping注解来指定字段之间的映射关系。在这个例子中,我们将Student的address字段映射到StudentDTO的ignoredField字段,这样它将被忽略。

最后,我们可以在我们的代码中使用这个映射器实例,如下所示:

Student student = new Student();
student.setName("Alice");
student.setAge(20);
student.setAddress("123 Main St");

StudentDTO studentDTO = StudentMapper.INSTANCE.studentToStudentDTO(student);

System.out.println(studentDTO.getName()); // Output: Alice
System.out.println(studentDTO.getAge()); // Output: 20
1
2
3
4
5
6
7
8
9

# 4. validator注解的使用

# 4.1 安装依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.2.3.Final</version>
</dependency>
1
2
3
4
5
6
7
8
9

# 4.2 写全局异常处理

@ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public <T> BaseResponse<T> processException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, msg);
    }
1
2
3
4
5
6

# 4.3 写配置类

@Configuration
public class ValidatorConfig {


    @Bean
    public Validator validator() {

        ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
                .configure()
                // 将fail_fast设置为true即可,如果想验证全部,则设置为false或者取消配置即可
                .addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();
        return factory.getValidator();
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 4.4 添加注解实现约束

//实体类

@NotBlank(message = "标题不能为空")
private String title;

@NotBlank(message = "内容不能为空")
private String content;

@NotEmpty(message = "标签不能为空")
private List<String> tags;

//controller方法上添加@Validated
public BaseResponse<Long> addQuestion(@RequestBody @Validated QuestionAddRequest questionAddRequest){
  //业务逻辑...
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#后端#springboot
上次更新: 2023/12/09 16:19:24
EasyCaptcha验证码存入redis的使用
Elasticsearch全文搜索

← EasyCaptcha验证码存入redis的使用 Elasticsearch全文搜索→

最近更新
01
element-plus多文件手动上传 原创
11-03
02
TrueLicense 创建及安装证书 原创
10-25
03
手动修改迅捷配置 原创
09-03
04
安装 acme.sh 原创
08-29
05
zabbix部署 原创
08-20
更多文章>
Copyright © 2023-2024 liyao52033
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式