Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unpredictable random @Id for Entity

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
}
like image 244
Francesco Galgani Avatar asked Dec 22 '17 00:12

Francesco Galgani


2 Answers

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
    }
}
like image 63
buræquete Avatar answered Nov 09 '22 10:11

buræquete


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

like image 12
Panup Pong Avatar answered Nov 09 '22 10:11

Panup Pong