Skip to content
Advertisement

How to include CHECK in JPA @Column columnDefinition?

I am trying to figure out syntax for columnDefinition in Column annotation when i want to add CHECK.

So far what i have tried:

Using JPA 2.2 (JavaEE 8) and openjpa as jpa provider.

Could not find anything in docs: https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Column.html

Error i am getting:

I can obviously see that Id CHAR(1) DEFAULT 'X', CHECK 'X' NOT NULL,... is not valid SQL syntax, but i do not know how to include that CHECK when i use JPA. Thanks in advance for any help.

Is it even possible to include CHECK constraint in column definition?

Advertisement

Answer

See this for example.

The SQL fragment that is used when generating the DDL for the column.

It is SQL that is used while creating the table and thus also might be database dependent stuff. The fragment is appended to the default column definition.

So the problem is not in the JPA usage but in the SQL syntax.

You were quite close with the correct syntax but you should think yet what is the actual check. For example this should work (at least with Postgres):

But of course the example CHECK is not sane since it allows only inserting ‘X’ as foo. However I cannot provide full answer since your CHECK('X') is unclear to me. Maybe you wanted to make column not nullable? Like:

or even better:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement