parsecer
parsecer

Reputation: 5106

Hibernate: how to auto generate an id that is a 36 base string

How do I go around auto generating an @Id that is not Integer/Long value, but rather a String which is a number in base 36?

e.g. if the next id is to be 58490, the String id attribute should be 194q.

@Entity
@Table(name = "persons")
public class Person  {
  @Id
  //?
  private String id;

  @Column
  private String name;
...
}
+--------+--------+
| base10 | base36 |
+--------+--------+
|    ... | ...    |
|  58490 | 194q   |
|  58491 | 194r   |
+--------+--------+

so that the actual persons table looks like:

+------+------+
|  id  | name |
+------+------+
| ...  | ...  |
| 194q | John |
| 194r | Jack |
+------+------+

Upvotes: 0

Views: 171

Answers (1)

Mubaraka Bharucha
Mubaraka Bharucha

Reputation: 206

You can create a custom annotation. Creating a custom annotation and put your logic in that annotation.

Another way is to write a converter :

public class DecimalToHexConverter implements AttributeConverter<String, String> {


    @Override
    public String convertToDatabaseColumn(String attribute) {

        // convert to hex
        return object;
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
        // convert back to decimal
        return object;
    }
}

Then apply this converter on your id.

  @Id
  @Convert(converter = DecimalToHexConverter.class)
  private String id;

Upvotes: 1

Related Questions