@OneToMany MySQLIntegrityConstraintViolationException

时间:2018-07-11 00:21:07

标签: json hibernate spring-boot

我在角色类和用户类之间有一个@OneToMany关系,并且在添加新用户时遇到一些问题,另一方面,我可以毫无问题地添加新角色。所以我不确定问题的原因,因为我确实对另外两个类使用了相同的方法,而且效果很好。

@Entity
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;
    @Column(name = "username", unique = true, nullable = false)
    private String username;
    @Column(name = "email", unique = true, nullable = false)
    private String email;   
    @Column(name = "password", nullable = false)
    private String password;
    @Column(name = "firstName", nullable = false)
    private String firstName;
    @Column(name = "lastName", nullable = false)
    private String lastName;
    @Column(name = "avatar", nullable = true)
    private String avatar;
    @ManyToOne
    @JoinColumn(name = "fk_role")
    @JsonBackReference
    private Role role;
}

@Entity
public class Role implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;    
    @Column(name = "roleName", unique = true, nullable = false)
    private String roleName;
    @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "role", fetch = FetchType.LAZY)
    @JsonManagedReference
    private Set<User> users = new HashSet<User>();
}

这是我为创建新用户而发出的JSON请求:

{
    "username":"xxxx",
    "email":"xxxx@gmail.com",
    "password":"xxxx",
    "firstName":"xxxx",
    "lastName":"xxxx",
    "avatar":null,
    "role":{
        "id":3
    }
}

这是用于创建新用户的JSON响应:

{
    "timestamp": "2018-07-10T22:30:26.385+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could  not execute statement",
    "path": "/users"
}

这是我在后端遇到的错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'email' cannot be null

有人可以帮我解决这个问题吗?

这是API后端代码:

//Create a new user
@RequestMapping(value="/users", method=RequestMethod.POST)
@ResponseBody
public User save(User u){
    return userRepository.save(u);
}

1 个答案:

答案 0 :(得分:1)

您应在@RequestBody之前添加User u批注,如下所示:

public User save(@RequestBody User u){
   return userRepository.save(u);
}