我试着通过Postman使用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'
这里是在userService实现中:
下面这行代码(BeanUtils
)参考自这里。
@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;
}
但是,如果我使用下面的代码,由于我在DTO中将user.getRole()
定义为 int
,但是在User
实体中将newUser.setRole()
定义为 Role
,因此setRole
方法是不适用
的。但是,如果我将User
实体中的setRole
更改为int
,那么我该如何告诉spring关于User
和Role
之间的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;
}
注意:我认为我只需要将
role
的输入参数作为提供的整数即可。