Skip to content

Commit 4dfe8f0

Browse files
hajarrshajar.qaibou_juliusbaer.com
andauthored
Co-authored-by: hajar.qaibou_juliusbaer.com <[email protected]>
1 parent 323012f commit 4dfe8f0

File tree

7 files changed

+141
-0
lines changed

7 files changed

+141
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.beanvalidation.application.controllers;
2+
3+
import com.baeldung.beanvalidation.application.entities.AppUser;
4+
import com.baeldung.beanvalidation.application.repositories.AppUserRepository;
5+
import jakarta.validation.Valid;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.http.HttpStatus;
8+
import org.springframework.http.ResponseEntity;
9+
import org.springframework.validation.BindingResult;
10+
import org.springframework.web.bind.annotation.*;
11+
12+
@RestController
13+
@RequestMapping("/api/app-users")
14+
public class AppUserController {
15+
16+
@Autowired
17+
private AppUserRepository appUserRepository;
18+
19+
@PostMapping
20+
public ResponseEntity<String> addAppUser(@Valid @RequestBody AppUser appUser, BindingResult result) {
21+
if (result.hasErrors()) {
22+
return new ResponseEntity<>(result.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
23+
}
24+
appUserRepository.save(appUser);
25+
return new ResponseEntity<>("AppUser created successfully", HttpStatus.CREATED);
26+
}
27+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.beanvalidation.application.entities;
2+
3+
import jakarta.persistence.*;
4+
import jakarta.validation.constraints.Email;
5+
import jakarta.validation.constraints.NotEmpty;
6+
import jakarta.validation.constraints.Size;
7+
import com.baeldung.beanvalidation.application.validation.UserUnique;
8+
9+
@Entity
10+
public class AppUser {
11+
12+
@Id
13+
@GeneratedValue(strategy = GenerationType.IDENTITY)
14+
private Long id;
15+
16+
@NotEmpty(message = "Username is required")
17+
@Size(min = 3, max = 50, message = "Username must be between 3 and 50 characters")
18+
@UserUnique
19+
private String username;
20+
21+
@NotEmpty(message = "Email is required")
22+
@Email(message = "Email should be valid")
23+
private String email;
24+
25+
// Getters and setters
26+
public Long getId() { return id; }
27+
public void setId(Long id) { this.id = id; }
28+
29+
public String getUsername() { return username; }
30+
public void setUsername(String username) { this.username = username; }
31+
32+
public String getEmail() { return email; }
33+
public void setEmail(String email) { this.email = email; }
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.beanvalidation.application.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.http.ResponseEntity;
5+
import org.springframework.validation.FieldError;
6+
import org.springframework.web.bind.MethodArgumentNotValidException;
7+
import org.springframework.web.bind.annotation.ControllerAdvice;
8+
import org.springframework.web.bind.annotation.ExceptionHandler;
9+
10+
import java.util.HashMap;
11+
import java.util.Map;
12+
13+
@ControllerAdvice
14+
public class GlobalExceptionHandler {
15+
16+
@ExceptionHandler(MethodArgumentNotValidException.class)
17+
public ResponseEntity<Map<String, String>> handleValidationException(MethodArgumentNotValidException ex) {
18+
Map<String, String> errors = new HashMap<>();
19+
20+
// Populate the map with field-specific error messages
21+
ex.getBindingResult().getAllErrors().forEach(error -> {
22+
String fieldName = ((FieldError) error).getField();
23+
String errorMessage = error.getDefaultMessage();
24+
errors.put(fieldName, errorMessage);
25+
});
26+
27+
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
28+
}
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.baeldung.beanvalidation.application.repositories;
2+
3+
import com.baeldung.beanvalidation.application.entities.AppUser;
4+
import org.springframework.data.jpa.repository.JpaRepository;
5+
import org.springframework.stereotype.Repository;
6+
7+
@Repository
8+
public interface AppUserRepository extends JpaRepository<AppUser, Long> {
9+
AppUser findByUsername(String username);
10+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.beanvalidation.application.validation;
2+
3+
import jakarta.validation.Constraint;
4+
import jakarta.validation.Payload;
5+
import java.lang.annotation.*;
6+
7+
@Documented
8+
@Constraint(validatedBy = UserUniqueValidator.class)
9+
@Target({ ElementType.FIELD })
10+
@Retention(RetentionPolicy.RUNTIME)
11+
public @interface UserUnique {
12+
String message() default "Username already exists";
13+
Class<?>[] groups() default {};
14+
Class<? extends Payload>[] payload() default {};
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.beanvalidation.application.validation;
2+
3+
import com.baeldung.beanvalidation.application.repositories.AppUserRepository;
4+
import jakarta.validation.ConstraintValidator;
5+
import jakarta.validation.ConstraintValidatorContext;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
8+
public class UserUniqueValidator implements ConstraintValidator<UserUnique, String> {
9+
10+
@Autowired
11+
private AppUserRepository appUserRepository;
12+
13+
@Override
14+
public boolean isValid(String username, ConstraintValidatorContext context) {
15+
return appUserRepository.findByUsername(username) == null;
16+
}
17+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,10 @@
11
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
2+
3+
spring.datasource.url=jdbc:h2:mem:testdb
4+
spring.datasource.driverClassName=org.h2.Driver
5+
spring.datasource.username=sa
6+
spring.datasource.password=password
7+
spring.jpa.hibernate.ddl-auto=update
8+
9+
# Disable Hibernate validation
10+
spring.jpa.properties.jakarta.persistence.validation.mode=none

0 commit comments

Comments
 (0)