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:

@Id
@Column(columnDefinition = "CHAR(1) DEFAULT 'X' ADD CHECK 'X'")
private char Id;

@Id
@Column(columnDefinition = "CHAR(1) DEFAULT 'X', CHECK 'X'")
private char Id;

@Id
@Column(columnDefinition = "CHAR(1) DEFAULT 'X', CHECK (Id = 'X')")
private char Id;

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:

Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: 42X01 : [0] Encountered "'X'" at line 1, column 52 {stmn
t 1524146915 CREATE TABLE Parish (Id CHAR(1) DEFAULT 'X', CHECK 'X' NOT NULL, church SMALLINT, email VARCHAR(255), name 
VARCHAR(255), officialName VARCHAR(255), phone VARCHAR(255), shortName VARCHAR(255), PRIMARY KEY (Id))} [code=30000, sta
te=42X01]

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):

@Column(columnDefinition = "CHAR(1) DEFAULT 'X' CHECK (Id = 'X')")
private char Id;

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:

@Column(columnDefinition = "CHAR(1) DEFAULT 'X' NOT NULL")

or even better:

@Column(columnDefinition = "CHAR(1) DEFAULT 'X'", nullable = false)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement