Tell Hibernate hbm2ddl to add MySQL enumeration columns for @ Generic annotated fields

I am creating a DB table using hbm2ddl with Java code similar to the following:

@Entity public class Filter { public enum Type { TypeA, TypeB; } @Enumerated(EnumType.STRING) private Type type; } 

It works fine, but for "type" a VARCHAR column is created, that is, the DDL code looks like this:

 CREATE TABLE IF NOT EXISTS `filter` (`type` varchar(255) DEFAULT NULL) 

But I want it to be:

 CREATE TABLE IF NOT EXISTS `filter` (`type` enum('TypeA','TypeB') NOT NULL) 

Is it possible to declare in Hibernate, preferably with annotations?

Or is there a way to extend SchemaUpdate and overwrite the method that displays the alter script part for an enum field as I like?

Background: the same database is used in part of the PHP project, and I want these invalid values ​​to be inserted.

+4
source share
2 answers

I find this to be difficult, because the java.sql.Types, which define the sql types processed by java, do not have an enum type (since this is not a standardized type according to SQL-92).

If this was random, you could create a custom hibernate type extending EnumType and setting sqlType accordingly, but since java.sql.Types doesn't handle it, I don't see how to use native sql enum.

Best wishes!

0
source

Although it seems that there is no way to automatically process MySQL 100% 100%, as Lucas pointed out in his answer, there is actually a simple outline method. You can use attribute columnDefinition annotations @Column , which appears to be designed specifically to create a custom DDL-code.

See excerpt documentation describing the attribute:

(Optional) The SQL fragment that is used to generate the DDL for the column.

By default, created SQL is created to create a column of the output type.

The NOT NULL is fairly standard and is supported by another nullable attribute.

So your property definition will look like this:

 @Enumerated(EnumType.STRING) @Column(columnDefinition = "enum ('TypeA', 'TypeB')", nullable = false) private Type type; 
+1
source

All Articles