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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With