I have the following code. Because the @Id
value is generated sequentially in my MariaDB
, it's not safe: I need to expose it in the clients. That's why I want a unpredictable random @Id
. How should I change the code?
@Entity
public class Item implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id; // Automatic generated value
// other fields, getters, setters & constructors
}
If not satisfied with default generators, you can define your own generator in the following manner;
@Entity
public class Item implements Serializable {
@Id
@GeneratedValue(generator = MyGenerator.generatorName)
@GenericGenerator(name = MyGenerator.generatorName, strategy = "a.b.c.MyGenerator")
private String id;
// rest of the entity
}
And the generator itself;
public class MyGenerator implements IdentifierGenerator {
public static final String generatorName = "myGenerator";
@Override
public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object object) throws HibernateException {
return UUID.randomUUID().toString().replace("-", "");
// or any other logic you'd like for generating unique IDs
}
}
Using Hibernate and UUID identifiers
The UUID hex generator is the oldest UUID identifier generator and it’s registered under the “uuid” type. It can generate a 32 hexadecimal UUID string value (it can also use a separator) having the following pattern: 8{sep}8{sep}4{sep}8{sep}4.
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(columnDefinition = "CHAR(32)")
@Id
private String id;
One thing of UUID identifiers which work for both MySQL(GenerationType.IDENTITY) and Oracle(GenerationType.SEQUENCE) for Hibernate auto key generation as one Entity class.
Advantages and disadvantages of GUID / UUID database keys
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With