DevShivmohan / Learning-everything

Learning for developer only
0 stars 1 forks source link

Spring boot entity validations,mapping and response #11

Open DevShivmohan opened 1 year ago

DevShivmohan commented 1 year ago

Inside entity class validate field with respected validations like that

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotEmpty(message = "First name is required")
    private String firstName;

    @NotEmpty(message = "Last name is required")
    private String lastName;

    @NotEmpty(message = "Email is required")
    @Email
    private String email;

    @NotEmpty(message = "Phone number is required")
    @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$",
             message="Mobile number is invalid")
    private String mobilePhone;

    @Past
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate birthday;

    @NotEmpty(message = "Communication preference is required")
    private String commPreference;
}

implement below code inside exception handler class, these are return to the client as a response

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getFieldErrors().forEach(error -> 
        errors.put(error.getField(), error.getDefaultMessage()));
    return errors;
}
DevShivmohan commented 1 year ago

Implementation of entity or DTO validation

Declare in Global exception handler


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler{
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException methodArgumentNotValidException){
        log.error("Args");
        Map<String,String> map=new HashMap<>();
        methodArgumentNotValidException.getBindingResult()
                .getAllErrors().forEach(error->map.put(((FieldError)error).getField(),error.getDefaultMessage()));
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(map);
    }
}

Validating in DTO or Entity

@Data
@Builder
public class AuthRequest {
    @NotBlank(message = "Username cannot be blank")
    @Size(min = 3,message = "Must be 3 chars")
    @Pattern(regexp = "[0-9a-zA-Z]+",message = "Username must contain alpha numeric value")
    private String username;
    private String password;
}

Enable validation during accept request body using @Valid annotation like below

@PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody AuthRequest authRequest){
        log.info("Request hits-"+authRequest);
        return authenticationService.login(authRequest);
    }

If you need extra information than please refer this Link

DevShivmohan commented 9 months ago

Mapping of collection with wrapper classes (Integer,Long,String etc) to the Entity example


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.Collections;
import java.util.Set;

@Entity
@Table(name = "business")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Business {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "business_id")
    private Integer id;

    private String name;

    @ElementCollection
    @CollectionTable(name = "user_ids",joinColumns = @JoinColumn(name = "business_id"))
    private Set<Integer> userIds= Collections.emptySet();
}
DevShivmohan commented 8 months ago

Relationship Mappings in JPA

Reference to learn mappings in JPA - Relationship mapping JPA

DevShivmohan commented 2 months ago

Managing infinite calls from entity to entity

image