Hibernate custom type mapping set length of char

Viewed 215

I'm currently implementing a custom type mapping in hibernate (Mapping UUIDs to char in order to set an index in oracle). I implemented the hibernate type UUIDType and UUIDJavaDescriptor and added them to our baseEntity (JPAEntity) via @TypeDef. The issue is that the columns are being generated as varchar(255) instead of varchar(36). Annotating UUID fields via @Column(length = 36, /* ... */) works as expected but I don't want to annotate all UUID fields within the project. Does anybody know a way to adapt the length of all UUID fields globally?

public class UUIDType extends AbstractSingleColumnStandardBasicType<UUID> {
  public static final UUIDType INSTANCE = new UUIDType();
  public static final String NAME = "uuid";
  public static final Size SIZE = new Size(0, 0, 36, Size.LobMultiplier.NONE);
  // define the column size                      ^^^

  public UUIDType() {
    super(VarcharTypeDescriptor.INSTANCE, UUIDJavaDescriptor.INSTANCE);
  }

  @Override
  public String getName() {
    return NAME;
  }

  // Override size related methods
  @Override
  protected Size getDictatedSize() {
    return SIZE;
  }

  @Override
  public Size[] dictatedSizes(Mapping mapping) throws MappingException {
    return new Size[] { SIZE };
  }

  @Override
  public Size[] defaultSizes(Mapping mapping) throws MappingException {
    return new Size[] { SIZE };
  }
}
public class UUIDJavaDescriptor extends AbstractTypeDescriptor<UUID> {
  public static final UUIDJavaDescriptor INSTANCE = new UUIDJavaDescriptor();

  public UUIDJavaDescriptor() {
    super(UUID.class, ImmutableMutabilityPlan.INSTANCE);
  }

  @Override
  public UUID fromString(String string) {
    if (StringUtils.isEmpty(string)) return null;
    return UUID.fromString(string);
  }

  @Override
  public <X> X unwrap(UUID value, Class<X> type, WrapperOptions options) {
    if (value == null) {
      return null;
    }

    if (String.class.isAssignableFrom(type)) {
      return (X) toString(value);
    }

    throw unknownUnwrap(type);
  }

  @Override
  public <X> UUID wrap(X value, WrapperOptions options) {
    if (value == null) {
      return null;
    }

    if (String.class.isInstance(value)) {
      return UUID.fromString((String) value);
    }

    throw unknownWrap(value.getClass());
  }
}
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Getter
@Setter
@ToString(callSuper = true)
@MappedSuperclass
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@TypeDefs({
  @TypeDef(typeClass = UUIDType.class, defaultForType = UUID.class, name = UUIDType.NAME)
})
public abstract class JPAEntity {
 // ...
}

Technical Details:

  • Apache Maven 3.6.3
  • openjdk 11.0.2
  • Hibernate-Core 5.4.30.Final
1 Answers

You can't change that, as the value 255 comes from the javax.persistence.Column annotation. Hibernate 6.0 will handle this properly, but for now, you'd simply have to set the length everywhere.

Related