views:

189

answers:

1

The following JPA column definition generates an "integer" data type by default on all databases (e.g. h2, mysql, postgres)

@Column(name = "type", nullable = false)
@Type(type = "com.mycompany.hibernate.usertype.GenericEnumUserType", parameters = {
        @Parameter(name = "enumClass", value = "com.mycompany.model.DegreeType"),
        @Parameter(name = "identifierMethod", value = "toInt"),
        @Parameter(name = "valueOfMethod", value = "fromInt") })
@NotNull
private DegreeType type;

I would like to use minimal storage for this field and hence would prefer to use the columnDefinition parameter for schema2ddl generation. But looks like tinyint is not supported in postgres, but is supported in other databases mentioned above.

Would it be possible to generate different SQL files based on the database type. 1. What would be the best approach to acheive this? 2. What would be the best data type (with minimal storage) which can be used for this purpose? Would that be smallint

+1  A: 

Since you're using custom type (why?), the underlying column definition(s) would be generated based on result of your type's sqlTypes() method. The actual SQL column type would be obtained from appropriate Dialect.

Thus, if sqlTypes() were to return new int[] {Types.TINYINT}, PostgresQL dialect would map it to int2 and H2 / MySQL to tinyint.

All that said, I would generally recommend to:

  1. Use built-in enum support via @Enumerated annotation.
  2. Store enum value as string rather than integer. Using the latter does conserve some space, but it introduces a huge potential problem: 3 months (years) down the line somebody changes the code by inserting another enum constant in the middle of your type and suddenly all your data becomes invalid. Disk space is cheap; dealing with issues like that isn't.

    @Enumerated(EnumType.STRING)
    @Column(name = "degree_type", nullable = false, length=!0)
    private DegreeType type;
    
ChssPly76
Thanks and appreciate the help, making the type as TINYINT did the trick. By the way I am storing enumerations as integers and hence this abstraction is needed on top of GenericEnum. Since my enum values are localizable, I can't use the @Enumerated annotation which stores all values as strings
Joshua