我尝试通过邮递员使用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
问题:它引发错误'Column 'role_id' cannot be null'
这是在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
方法是not applicable
,因为我在DTO中将user.getRole()
定义为int
,但在DTO中定义了newUser.setRole()
User
个实体为Role
。但是,如果我将setRole
实体中的User
更改为int
,那么我该如何告诉弹簧ManyToOne
和{{1 }}?
User
注意:我想我只想像上面提供的那样将Role
的输入参数设为@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;
}
。
答案 0 :(得分:2)
由于您在请求中获得的角色为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
的类型为Role
,而在源(用户)中,字段的类型仅为int。