Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Check Annotation

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?

like image 988
blahblah Avatar asked Aug 13 '15 08:08

blahblah


People also ask

What is hibernate annotation?

Hibernate annotations are the newest way to define mappings without the use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping.

Is ID mandatory in hibernate?

Yes, hibernate requires an Id. Sometimes if you are dealing with a legacy database that for whatever reason does not have a key, you can define the key in Hibernate to be a composite key of all the columns for example, as this will be guaranteed to be unique.

What are hibernate validators?

Hibernate Validator allows to express and validate application constraints. The default metadata source are annotations, with the ability to override and extend through the use of XML. It is not tied to a specific application tier or programming model and is available for both server and client application programming.

Which annotation will be used to fetch the property to attribute?

The fetch attribute of the @ManyToMany annotation allows you to define the FetchType that shall be used for this association. The FetchType defines when the persistence provider fetches the referenced entities from the database.


1 Answers

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.

like image 167
Tunaki Avatar answered Sep 30 '22 21:09

Tunaki