我有两个实体,我想保存到数据库中,分别是Payment和PaymentItem。付款可以有更多的PaymentItems。
主要实体:
@Entity(name = "payment")
public class PaymentEntity {
@Id
private UUID id;
@NotNull // if I remove this... interesting things happen
@OneToMany(cascade = CascadeType.ALL)
@Valid
private List<PaymentItemEntity> items;
// getters, setters
}
第二个实体
@Entity(name = "payment_item")
public class PaymentItemEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String code;
}
因此,我用1 PaymentItem填充了Payment,然后尝试保存它。 请注意,“付款”没有自动生成的ID,我从其他地方获得了ID,而是手动进行了设置。
现在,发生的事情是,当我尝试保存它时,Hibernate进入数据库以查看是否存在现有条目及其项(不是,数据库为空)。
我知道这一点是因为我打开了休眠调试日志记录,并且看到了:
2018-06-22 14:34:33.939 DEBUG 3915 --- [nio-8100-exec-2] o.h.e.i.DefaultMergeEventListener : EntityCopyObserver strategy: disallow
2018-06-22 14:34:33.940 DEBUG 3915 --- [nio-8100-exec-2] org.hibernate.loader.Loader : Loading entity: [ro.vdin.entity.PaymentEntity#60587d84-3ae6-3f1e-b63e-fa8b6658d669]
然后失败,并发生以下异常:
javax.validation.ConstraintViolationException: Validation failed for classes [ro.vdin.entity.PaymentEntity] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=items, rootBeanClass=class ro.vdin.entity.PaymentEntity, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:140) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:205) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:82) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
即使我最初的Payment实体列出了1个项目(因此,它也不为空)。
有趣的是,如果我删除@NotNull批注,则所有内容都将保存到数据库中-付款,PaymentItem和它们之间的关系(Hibernate创建一个正确填充的关联表)。
(基本上,因为设置了实体的ID,所以hibernate尝试合并它,而不是将其保存到db。)
我该怎么做才能在列表项上保留@NotNull批注? 而且,我可以做些什么,使其不从数据库加载任何内容并直接保存吗?
答案 0 :(得分:0)
例如,您尚未传递连接列@joinColumn。
@Entity(name = "payment")
public class PaymentEntity {
@Id
@GeneratedValue(strategy = IDENTITY)
private UUID id;
@NotNull
@OneToMany(cascade = CascadeType.ALL)
@Valid
private List<PaymentItemEntity> items;
// getters, setters
}
//Child Class
@Entity(name = "payment_item")
public class PaymentItemEntity {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
private String code;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id")// for Example i have passed id you have pass join column name
private PaymentEntity paymentEntity;
// getters, setters
}