休眠检查注解 [英] Hibernate Check Annotation
问题描述
我有一个包含三个字段的表,例如a,b,c.我想添加一个约束,以确保如果a不为null,则b和c也不为null.我已经使用下面的SQL完成了
I have a table with three fields, say a, b, c. I would like to add a constraint ensuring that if a is not null, then also b and c are not null. I have done that using following SQL
ALTER TABLE sample
ADD CONSTRAINT no_nulls
CHECK (CASE WHEN a IS NOT NULL THEN b IS NOT NULL AND c IS NOT NULL END)
有没有一种方法可以使用休眠注释@Check来达到相同的效果?
Is there a way to achieve same effect using hibernate annotation @Check?
我找不到带有该注释的有用示例,开发人员是否倾向于完全不使用它?
I can't find a helpful example with that annotation, do developers tend not to use it at all?
推荐答案
是的,如果在类级别使用@Check
是可能的,如下所示:
Yes it is possible if @Check
is used at class level like this:
@Entity
@Check(constraints = "COL_A IS NULL OR (COL_B IS NOT NULL and COL_C IS NOT NULL)")
public class Sample {
@Column(name = "COL_A")
private Long a;
@Column(name = "COL_B")
private Long b;
@Column(name = "COL_C")
private Long c;
}
(请注意,我使用@jarlh注释重写了您的条件.). @Check
批注的constraints
子句需要引用@Column
的name
属性(它必须是纯SQL).
(Note that I rewrote your condition using @jarlh comment.). The constraints
clause of @Check
annotation needs to refer to the name
attribute of @Column
(it must be pure SQL).
@Check
注释必须处于类级别.
@Check
annotation needs to be at class level because of a Hibernate bug.
这篇关于休眠检查注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!