1

Now, we define the id as String type with JPA annotation:

@Id
private String id;

Now we want to save UUID as binary in Mysql, I know JPA have one way to implement it like below:

@Id
@Column(columnDefinition = "BINARY(16)")
private UUID id;

But it is big effort to modify String to java.util.UUID type, because I need to modify huge code (a lots of test cases, other calls and so on, anyway we can't do this).

Then I try to use JPA Converter to convert String to bytes and save it, but I found JPA doesn't allow define converter on ID field.

So, please who could provide some possible ways for saving UUID as binary without changing the original String type.

1 Answer 1

1

You can use uuid2. It offers a broader type range to choose from:

  • java.lang.UUID
  • a 16 byte array
  • a hexadecimal String value

Your id will like:

@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)")
@Id
private UUID id;
Sign up to request clarification or add additional context in comments.

2 Comments

I want to define the field as String, but store it as binary, because I don't want to refactor a lot of code
@Tony instead of refcator your code, you can just add @PrePersist (automatic property set before any database persistence) in your entity, e.g-> @PrePersist protected void onCreate() { your uuid generation logic... } now you can add this in your entity class and you don't need to take care of refactor another code. here is it doc docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.