本文介绍了如何手动为@GeneratedValue设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Spring Data JPA进行Spring引导. Postgres数据库.
Have a Spring boot with Spring Data JPA. Postgres DB.
一般实体:
@Entity
@Table
class Entity {
@Id
@GeneratedValue
private int id;
}
当我尝试使用指定的id
值进行输入时,结果我看到它被@GeneratedValue
忽略并生成.
when I try to make an entry with a specified id
value, as a result I see that it is ignored and generated by @GeneratedValue
.
如何克服这个问题?
推荐答案
发布解决方案,在对整个持久性过程进行调试后我来到了解决方案(并未说明这是正确的方法,但我确实没有这样做)找到也许我配置有误"的任何地方):
Posting the solution, to which I came after doing a debug of the whole persist process (not stating that this is the right way, but I literally didn't find any spot of "maybe I configured something wrong"):
public class MyGenerator extends SequenceStyleGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
return Optional.of(object)
.filter(Entity.class::isInstance)
.map(Entity.class::cast)
.map(Entity::getId)
.filter(i -> i > 0)
.map(Serializable.class::cast)
.orElse(super.generate(session, object));
}
)
和实体:
@Entity
class Entity implements Serializable {
@GenericGenerator(name = "myGenerator", strategy = "org.a.b.c.generators.MyGenerator")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "myGenerator")
private Integer id;
}
这篇关于如何手动为@GeneratedValue设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!