Hibernate Check Annotation

落花浮王杯 提交于 2019-12-22 04:53:09

问题


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)

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?


回答1:


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;

}

(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 annotation needs to be at class level because of a Hibernate bug.



来源:https://stackoverflow.com/questions/31983454/hibernate-check-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!