我尝试通过邮递员使用post方法对我的spring boot应用程序进行API调用.
这是输入:
{
"username": "name",
"password": "1234",
"age": 12,
"salary": 5000,
"role": 1
}
这是控制器中的代码:
@RequestMapping(value = "/signup", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> saveUser(@RequestBody UserDto user) {
try {
System.out.println(user.getUsername()); // => name
System.out.println(user.getPassword()); // => 1234
System.out.println(user.getSalary()); // => 5000
System.out.println(user.getRole()); // => 1
System.out.println(user.getAge()); // => 12
userService.save(user);
return ResponseEntity.ok().body("insert done");
} catch (Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
这是我的User.java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@Column
@JsonIgnore
private String password;
@Column
private long salary;
@Column
private int age;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "role_id")
private Role role;
// getters and setters
这是我的Role.java
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "role_name", nullable = false)
private String roleName;
// getters and setters
这是我的UserDto.java
private String username;
private String password;
private int age;
private long salary;
private int role;
// getters and setters
这是我的RoleDto.java
private Long id;
private String roleName;
// getters and setters
问题:它引发错误“列’role_id’不能为空”
这是在userServiceImpl中:
第(BeanUtils)行下方是here.
@Override
public User save(UserDto user) throws Exception {
User newUser = new User();
BeanUtils.copyProperties(user, newUser, "password");
newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
try {
userDao.save(newUser);
} catch (Exception e) {
throw new Exception(e);
// this throw "Column role_id cannot be null"
}
return newUser;
}
但是,如果我使用以下代码,则setRole方法不适用,因为我在DTO中将user.getRole()定义为int,但在User实体中将newUser.setRole()定义为Role.但是,如果我将User实体中的setRole更改为int,那我该如何告诉用户和角色之间的ManyToOne关系呢?
@Override
public User save(UserDto user) throws Exception {
User newUser = new User();
newUser.setUsername(user.getUsername());
newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
newUser.setAge(user.getAge());
newUser.setSalary(user.getSalary());
newUser.setRole(user.getRole()); // here is the problem
try {
userDao.save(newUser);
} catch (Exception e) {
throw new Exception(e);
}
return newUser;
}
注意:我想我只想使角色的输入参数只是上面提供的整数.
最佳答案
由于您在请求中获得的角色为1,因此您应该执行以下操作:
Role role = new Role();
role.setId(user.getRole());
role.setRoleName("some name");
newUser.setRole(role);
在代码的第一部分中,问题可能出在这里BeanUtils.copyProperties(user,newUser,“ password”);,如果您尝试在该行之后调试或打印newUser,您将看到BeanUtils无法正确填充所有您的newUser对象的字段.这是因为在目标(newUser)中,字段角色的类型为Role,而在源(用户)中,该字段的类型仅为int.