user.java
Code: Select all
@Entity
@Table(name="users")
@JsonIdentityInfo(generator= ObjectIdGenerators.IntSequenceGenerator.class, property="id")
public class User {
@Transient
Logger logger = LogManager.getLogger(getClass());
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int ID;
@NotNull
private String username;
@NotNull
private String Last_Name;
@NotNull
private String First_Name;
private String Title;
}
usercontroller.java < /p>
Code: Select all
@PostMapping("/user")
public ResponseEntity test(@RequestBody Map object) throws Exception {
try {
userService.createAccount(object);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
return ResponseEntity.ok("Account was added successfully");
}
Code: Select all
public void createAccount(Map accountObject) throws Exception {
logger.trace("Entering createAccount(). account=" +accountObject);
User user = new User( ??? );
userRepository.save(user);
}
< /code>
Ich habe darüber nachgedacht, einen neuen Konstruktor in user zu erstellen.public User(Map fieldsMapping) {
this(
getValue(fieldsMapping, "username", String.class),
getValue(fieldsMapping, "last_name", String.class),
getValue(fieldsMapping, "first_name", String.class),
);
}
// Helper method for type-safe value extraction.
private static T getValue(Map map, String key, Class clazz) {
Object value = map.get(key);
if (value == null) {
return null;
}
return clazz.cast(value);
}