为实体生成不可预测的随机@Id [英] Generate unpredictable random @Id for Entity
本文介绍了为实体生成不可预测的随机@Id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码.因为@Id
值是在我的MariaDB
中顺序生成的,所以它并不安全:我需要在客户端中公开它.这就是为什么我想要一个不可预测的随机@Id
.我应该如何更改代码?
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
}
生成器本身;
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
}
}
这篇关于为实体生成不可预测的随机@Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文