我正在尝试找到在id
中生成Entity
Spring
的最佳做法
符合以下要求:
我无法使用uuid
,因为它不符合要求。
我目前正在使用Hibernate
版本4.3.1 - 但如果需要,我可能会更新。
答案 0 :(得分:3)
您可以使用自定义ID生成器生成ID
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@GenericGenerator(name = "XyzIdGenerator",
strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
parameters = {
@Parameter(name = "sequence", value = "xyz_id_sequence")
})
public BigInteger getId()
{
return id;
}
package com.mycompany.myapp.id;
import org.hibernate.id.SequenceGenerator;
public class BigIntegerSequenceGenerator
extends SequenceGenerator
{
@Override
public Serializable generate(SessionImplementor session, Object obj)
{
...
}
}
并在generate函数中定义逻辑。
答案 1 :(得分:1)
我用这种方式解决了问题:
package com.project.generator;
import ...
public class IdGenerator extends SequenceGenerator
{
Random r = new Random();
private Logger log = LoggerFactory.getLogger(IdGenerator.class);
Session session;
int attempt = 0;
public int generate9DigitNumber()
{
int aNumber = (int) ((Math.random() * 900000000) + 100000000);
return aNumber;
}
@Override
public Serializable generate(SessionImplementor sessionImplementor, Object obj)
{
session = (Session) sessionImplementor;
Integer id = generateRandomIndex();
return id;
}
public Integer generateRandomIndex()
{
for (int i = 0; i < 3; i++)
{
log.info("attempt: " + i);
Integer a = generate9DigitNumber();
log.info("index: " + String.valueOf(a));
if (session.get(Xyz.class, a) == null)
{
log.info("not found this id");
return a;
} else
{
log.info("found this id");
}
}
for (int i = 100000000; i < 999999999; i++)
{
log.info("Is id free: " + i);
if (session.get(Xyz.class, i) == null)
{
log.info("id is free: " + i);
return i;
}
}
return null;
}
}
实体类:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IdGenerator")
@GenericGenerator(name = "IdGenerator",
strategy = "com.project.generator.IdGenerator",
parameters = {
@Parameter(name = "sequence", value = "xyz_id_sequence")
})
private Integer id;