简体   繁体   English

如何使用自动增量ID在JPA中的实体中设置另一个变量

[英]How to use auto increment ID to set another variable in the entity in JPA

I have an auto increment key in my entity. 我的实体中有一个自动递增键。

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;

I have another variable data in the object which is created based on the id mentioned above. 我在基于上述ID创建的对象中还有另一个变量数据

For ex: 例如:

private String data;

public String setData(String str){
   this.data = str + this.getId();
}

How can I set data variable while creating the object. 创建对象时如何设置data变量。

I have used PrePersist annotation before which is not useful in this case. 我使用过PrePersist批注,在这种情况下,此批注无用。

You can't generate the id before saving the actual document . 保存实际document之前,您无法生成ID。 All you can do is, save the document, set the data part and save it again eg 您所能做的就是保存文档,设置数据部分,然后再次保存,例如

Document saved = jpaRepository.save(document);
saved.setData(saved.getId() + "blah");
jpaRepository.saveAndFlush(saved);

You can execute these steps under a transaction to maintain consistency. 您可以在事务下执行这些步骤以保持一致性。

You would have to use a database trigger as the value of an ID set through IDENTITY isn't available until after the insert occurs. 您将不得不使用数据库触发器,因为通过IDENTITY设置的ID的值直到插入发生后才可用。 You would then need to use a provider specific method to get the value set through a trigger, such as EclipseLink's eclipse.org/eclipselink/documentation/2.5/jpa/extensions/… . 然后,您将需要使用提供程序特定的方法来通过触发器获取设置的值,例如EclipseLink的eclipse.org/eclipselink/documentation/2.5/jpa/extensions/…。 Or you can use persist, flush to force the insert which should obtain the ID value, and then update your field value. 或者,您可以使用persist,flush强制插入应获得ID值的插入,然后更新您的字段值。 An alternative is to use table sequencing or some other generation type that allows preallocation, so the id value is available on persist. 一种替代方法是使用表排序或其他允许预分配的生成类型,因此id值在持久化时可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM