HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaspringMinor

Customize data types in a generated model with hibernate

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
generatedwithcustomizetypeshibernatedatamodel

Problem

I have a Spring/Hibernate application with the following domain class (irrelevant code stripped for brevity):

@Entity
@Data
public class Program implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long tid;

    @Column
    @Convert(converter = ProgramStatusConverter.class)
    private ProgramStatus status;

    @Column
    @Length(max=64)
    private String containerId;

    @Column
    private String sourceCode;

    @Column
    private String compilationOutput;

    @Column
    @OneToMany(fetch=FetchType.LAZY, mappedBy="program")
    private Set executions;
}


The problem is that the database schema (currently an in-memory h2 database) is generated when I startup the application. It works fine in almost all cases, but the "compilationOutput" and "sourceCode" columns are generated as VARCHAR(255), which is too short.

The solution I used was simply to add @Length(max=10000) on the two columns, but I don't like the solution for two reasons:

  • It's a semantic annotation and I'm using it to solve a purely technical issue. I have absolutely no reason to limit these fields to 10000 characters.



  • What if I get a sourceCode that's longer than 10000 characters ? This solution is not a real solution.



Is there a better way ?

Solution

It's not unreasonable that a maximum length should be specified for a field that is backed by a VARCHAR. In some frameworks, for example Django (Python), a max_length parameter is mandatory to create a CharField, but optional for a TextField. This makes sense: how else can the framework know the size of the column. A VARCHAR column needs a max size.

Make the maximum size a conscious design decision when using a relational database as storage. If the data is text and you need to support arbitrary length, then in the database it should be stored as a TEXT field instead of a VARCHAR. For that, use @Column(columnDefinition="text") or @Type(type="text"), as @ferada said in a comment,
and as discussed in this related post.

You remarked in a comment that H2 used the type VARCHAR(2147483647).
That's an irrelevant implementation detail of how H2 supports TEXT type.
It's indeed a bit funny.

Context

StackExchange Code Review Q#106808, answer score: 2

Revisions (0)

No revisions yet.