休眠检查注解 [英] Hibernate Check Annotation

查看:81
本文介绍了休眠检查注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三个字段的表,例如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子句需要引用@Columnname属性(它必须是纯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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆