简体   繁体   English

即使使用级联 = CascadeType.ALL POST/PUT/DELETE 方法时也会出现限制休眠异常

[英]Getting contraint hibernate exception when POST/PUT/DELETE Method even with using cascade=CascadeType.ALL

I'm trying to add a new Object to the h2-memory data base with POST Rest API.我正在尝试使用 POST Rest API 向 h2 内存数据库添加一个新对象。 I got this error : nested exception is org.hibernate.exception.ConstraintViolationException我收到此错误:嵌套异常是 org.hibernate.exception.ConstraintViolationException

In my Expense Entity I had put @ManyToOne(cascade=CascadeType.ALL) so it's not supposed to create the category object before creating the expense object , isn't?在我的费用实体中,我已经放置了@ManyToOne(cascade=CascadeType.ALL)所以它不应该在创建费用对象之前创建类别对象,不是吗?

Thanks in advance.提前致谢。 Here is my entites: public class Expense {这是我的实体:公共课费用 {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
private String description;
@Column(name = "expense_date")
private Instant expenseDate;
@Column(name = "location")
private String location;
@ManyToOne(cascade={CascadeType.ALL})
@Nullable
@JoinColumn(name = "category_id", referencedColumnName = "id", nullable = false)
private Category category;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)
@Nullable
@JsonIgnore
private User user;}

Category Class public class Category {类别类公共类类别{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@NonNull
private String name;}

User Class: public class User {用户类:公共类用户{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
private String name;
private String email;}

Problem solved when I removed nullable=false from @JoinColumn.当我从@JoinColumn 中删除 nullable=false 时问题解决了。 because in Post method , I did not provide the id because it's generated so it's theorically nullable因为在 Post 方法中,我没有提供 id 因为它是生成的所以理论上可以为空

You have an error in your definition of Expense class.您对费用类的定义有误。 The annotation @Nullable - allows NULL values, and nullable = false - don`t allow.注释@Nullable - 允许 NULL 值,而 nullable = false - 不允许。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM