@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private UUID userId;
@Column(nullable = false)
@NotBlank(message = "Name is Required")
private String name;
@Column(nullable = false)
@NotBlank(message = "Password hash is required")
@Size(min = 8, message = " Password must be more than 8 characters and alphanumeric ")
@Alphanumeric(message = "password must be alpahanumeric")
private String hash;
@Column(nullable = false, unique = true)
@NotBlank(message = "Username is required")
@Size(min = 5, max = 20, message = "Username must be between 5 and 20 characters")
private String username;
// a temporary variable to use in controller to check if roleId is valid in the
// Role entity
@Column(name = "user_role", insertable = false, updatable = false)
private Integer roleId;
@ManyToOne
@JoinColumn(name = "user_role", nullable = false, referencedColumnName = "id")
private Role role;
public User() {
This is how I setup my user class in a model package.
@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody @Valid User user, BindingResult bindingResult) {
// Check for validation errors
if (bindingResult.hasErrors()) {
String errorMessage = bindingResult.getAllErrors().get(0).getDefaultMessage();
logger.info("Validation error: {}", errorMessage);
return new ResponseEntity<>("Validation error: " + errorMessage, HttpStatus.BAD_REQUEST);
}
// Check if username already exists
Optional<User> userOptional = userRepository.findByUsername(user.getUsername());
if (userOptional.isPresent()) {
return new ResponseEntity<>("Username already exists", HttpStatus.BAD_REQUEST);
}
// Ensure roleId is provided in the JSON request
Integer roleId = user.getRoleId();
if (roleId == null) {
return new ResponseEntity<>("Role ID is required", HttpStatus.BAD_REQUEST);
}
// Fetch the Role from repository based on roleId
Optional<Role> optionalRole = roleRepository.findById(roleId);
if (!optionalRole.isPresent()) {
return new ResponseEntity<>("Role not found", HttpStatus.BAD_REQUEST);
}
// Set the fetched Role to the User object
Role role = optionalRole.get();
user.setUserRole(role);
// Save the user to the database
userRepository.save(user);
return ResponseEntity.ok("User registered successfully");
}
And my Postmapping for registering. It seems that my controller does not run any validations and skips the first if block statement, I am able to register with empty fields. I started Java recently and this is my first springboot project. Still learning my way around.
I checked if I have the right dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Also tried creating a UserDto class but seem to be facing more issues.
public class UserDto {
@NotBlank(message = "Name is Required")
private String name;
@NotBlank(message = "Password hash is required")
@Size(min = 8, message = " Password must be more than 8 characters and alphanumeric ")
@Alphanumeric(message = "password must be alpahanumeric")
private String hash;
@NotBlank(message = "Username is required")
@Size(min = 5, max = 20, message = "Username must be between 5 and 20 characters")
private String username;
// a temporary variable to use in controller to check if roleId is valid in the
// Role entity
private Integer roleId;
private Role role;
public User toUser() {
return new User()
.setName(name)
.setUsername(username)
.setHash(hash)
.setRoleId(roleId)
.setUserRole(role);
}
}
In my public User toUser() im getting setUsername(String) not resolved. Ive checked if ive properly imported everything and when i created this file i removed the validations from my Users class. Not sure how to get about it