Код: Выделить всё
@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() {
Код: Выделить всё
@PostMapping("/register")
public ResponseEntity 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 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 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");
}
Я проверил, правильные ли у меня зависимости
Код: Выделить всё
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.3.0
com.example
management_tool
0.0.1-SNAPSHOT
management_tool
Demo project for Spring Boot
17
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-validation
org.springframework.boot
spring-boot-devtools
runtime
true
org.postgresql
postgresql
runtime
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
1.18.24
provided
io.jsonwebtoken
jjwt
0.9.1
io.jsonwebtoken
jjwt-api
0.11.5
io.jsonwebtoken
jjwt-impl
0.11.5
runtime
io.jsonwebtoken
jjwt-jackson
0.11.5
runtime
javax.validation
validation-api
2.0.1.Final
org.hibernate.validator
hibernate-validator
org.springframework.boot
spring-boot-configuration-processor
3.3.0
true
org.slf4j
slf4j-api
${slf4j.version}
ch.qos.logback
logback-classic
${logback.version}
org.mindrot
jbcrypt
0.4
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-maven-plugin
Код: Выделить всё
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);
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... ing-for-me
Мобильная версия