【问题标题】:@OneToMany MySQLIntegrityConstraintViolationException@OneToMany MySQLIntegrityConstraintViolationException
【发布时间】:2018-12-18 21:49:54
【问题描述】:

我在角色类和用户类之间有@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);
}

【问题讨论】:

  • 您能发布您的 API 后端代码吗?看起来,您的“电子邮件”属性正在逐渐变为空。
  • 您确定您的 JSON 请求的 "role" : { "id" : 3 } 创建了一个有效的 Role 对象来持久化吗?
  • 您能否在填充用户实体的位置显示您的代码
  • @SazzadurRahaman 我添加了您要求的代码

标签: json hibernate spring-boot


【解决方案1】:

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

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

【讨论】:

  • 哎呀我没有注意到缺少 @RequestBody ,谢谢!
  • 很高兴为您提供帮助! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
相关资源
最近更新 更多