Solorad Solorad - 5 months ago 43
Java Question

Entity generated string id length to 32

I have preconfigured database, which I am not able to change. Primary Key for application is String with max length 32.
I have hibernate entity, that is currently using

uuid2
strategy to generate application ids. Problem is in fact, that UUID length is 36, but I need 32. How is it better for me to generate ids for Application?

Bellow is simplified version of my current entity.

@Entity
public class Application {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String applicationId;

private String name;
}

Answer

May be you can try something like this. You can create a PrePersist method that can modify the value before persisting.

@PrePersist
public void initializeUUID() {
    if (applicationId == null) {
        applicationId = UUID.randomUUID().toString().subString(0, 32);
    } else {
        applicationId = applicationId.toString().subString(0, 32);
    }
}
Comments