7

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 } 
1

2 Answers 2

13

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 } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Your solution seems to provide random IDs. I customized the code of the generator with the suggestions in this discussion: stackoverflow.com/questions/41107/…
12

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

1 Comment

Thanks. However this solution provides IDs that are not too much random. For example, I obtained these two Id that are quite similar: "8a80828f607e1ab401607ef58ec90000" and "8a80828f607e1ab401607ef83e910001". Also the third one is similar: "8a80828f607e1ab401607efd76e20002".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.