arcy
arcy

Reputation: 13123

Hibernate only sets length within @Column on field, not attribute

I have some classes with which I'm exploring Hibernate. One of them has a name field, and I attempted to set the length of it with the following:

private String firstname;
@Column(length=25)
public String getFirstName() { return firstName; }
public void setFirstName(String first) { this.firstName = first; }

I did this with several fields, all in the same pattern -- I put the @Column on the property firstName instead of on the field firstName. I have read that this determines how the framework accesses your field's information -- either directly from the field, or from the getter/setter of the field.

The idea that length can be put in @Column in that position is confirmed somewhat in the documentation; in the Hibernate Reference Documentation, in section 5.1.4.1.4., "Declaring column attributes", it has the following lines:

@Column(updatable = false, name = "flight_name", nullable = false, length=50)
public String getName() { ... }

so they put the length attribute on @Column in front of a getter.

The problem is that it doesn't work. My little test program adds a property for hbm2ddl.auto to "create", so that it drops everything and re-creates it; the configuration also echoes the generated SQL. With @Column in front of the getter, not the field, the generated field is VARCHAR(255), same as without @Column.

When I move @Column to be in front of the field instead, it is created with the designated length of 25.

Is this a bug, or am I missing something (else) about the configuration of Hibernate fields with annotations? Unfortunately I don't want the other attributes mentioned in the docs, and I would think it strange that you had to specify one of those to get length recognized anyway.

Upvotes: 0

Views: 641

Answers (1)

David Levesque
David Levesque

Reputation: 22441

If you want to use mixed access mode (i.e. use annotations on fields for some properties and on getters for others) you have to take a few extra steps.

First, set the default access type for the entity. For example, this will set the default access type to FIELD:

@Entity
@Access(AccessType.FIELD)
public class MyEntity { … }

Then for the properties that you want to annotate on the getters, explicitly set the access type to PROPERTY:

@Access(AccessType.PROPERTY)
@Column(length=25)
public String getFirstName() { return firstName; }

Upvotes: 1

Related Questions