Question

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

Was it helpful?

Solution

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;
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top