我尝试在 /addNewUser 端点上使用以下 POST 请求创建新用户:-
发布请求
{
"username" : "abc",
"password" : "123",
"enabled" : "true",
"authorities": [{
"authority" : "ROLE_USER"
}]
}
UserController 类:-
@PostMapping("/addNewUser")
public UserModel addNewUser(@RequestBody UserModel user) {
return userService.addNewUser(user);
}
UserService 类:-
public UserModel addNewUser(UserModel user) {
return userRepository.saveAndFlush(user);
}
UserRepository接口(interface)
public interface UserRepository extends JpaRepository<UserModel, String> {
}
但我遇到以下异常:-
2020-04-30 21:14:00.441 ERROR 23653 --- [nio-8080-exec-7] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: null value in column "authority" violates not-null constraint
Detail: Failing row contains (null, null).
2020-04-30 21:14:00.450 ERROR 23653 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [authority]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: null value in column "authority" violates not-null constraint
Detail: Failing row contains (null, null).
UserModel 类
@Entity
@Table(name = "users")
public class UserModel {
@Id
@Column(name = "username", unique = true, nullable = false)
private String username;
@Column(name = "password")
private String password;
@Column(name = "enabled")
private boolean enabled;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@JsonManagedReference
private List<AuthoritiesModel> authorities;
//getters and setters
}
AuthoritiesModel 类:-
@Entity
@Table(name = "authorities")
public class AuthoritiesModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name="username", unique = false, nullable=false)
private UserModel user;
@Id
@Column(name = "authority")
private String authority;
//getters and setters
}
最初,我认为我的发布请求或 Jackson API 的反序列化存在一些问题,因此我打印了 Controller 方法中 UserModel 字段的值,并且所有值都已正确设置,包括 AuthoritiesModel。但是当我尝试保留 UserModel 对象时,它会抛出异常。
更新1:
如果我在没有权限的情况下发布请求,它不会抛出任何异常,但我得到的权限为 null 作为响应。
发布请求
{
"username" : "abc",
"password" : "123",
"enabled" : "true"
}
发布回复
{
"username": "abc",
"password": "123",
"enabled": true,
"authorities": null
}
最佳答案
反序列化请求正文时,AuthoritiesModel
上没有设置 UserModel
。
你可以尝试这样的事情:
public UserModel addNewUser(UserModel user) {
List<AuthorityModel> authorities = user.getAuthorities();
authorities.stream().forEach(authority -> authority.setUser(user);
return userRepository.saveAndFlush(user);
}
关于java - ManyToOne 双向关系中 POST 请求上的 org.hibernate.exception.ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61529675/