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
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
Francesco Galgani
  • 6,137
  • 3
  • 20
  • 23

2 Answers2

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
    }
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
  • 1
    Thanks. Your solution seems to provide random IDs. I customized the code of the generator with the suggestions in this discussion: https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string – Francesco Galgani Dec 22 '17 at 17:22
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

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Panup Pong
  • 1,871
  • 2
  • 22
  • 44
  • 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". – Francesco Galgani Dec 22 '17 at 17:20